iPhone SDK: come si fa a giocare il video in vista? Piuttosto che a schermo intero
-
13-09-2019 - |
Domanda
Sto cercando di riprodurre il video in UIView
, quindi il mio primo passo è stato quello di aggiungere una classe per quella vista e avviare la riproduzione di un filmato in esso utilizzando questo codice:
- (IBAction)movie:(id)sender{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.scalingMode = MPMovieScalingModeAspectFill;
[theMovie play];
}
Ma questo solo si blocca l'applicazione quando si utilizza questo metodo all'interno di essa la propria classe, ma va bene altrove. Qualcuno sa come giocare il video in vista? ed evitare che venga a schermo intero?
Soluzione
A partire dalla 3.2 SDK è possibile accedere alla proprietà vista MPMoviePlayerController
, modificare la sua struttura e aggiungerlo alla vostra gerarchia della vista.
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
player.view.frame = CGRectMake(184, 200, 400, 300);
[self.view addSubview:player.view];
[player play];
C'è un esempio qui: http://www.devx.com/wireless/Article / 44642/1954
Altri suggerimenti
Il modo migliore è quello di utilizzare i livelli invece di visite:
AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; //
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[player play];
Non dimenticate di aggiungere quadri:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
Guardando il codice, è necessario impostare la cornice di vista del film del controller giocatore, e anche aggiungere vedere il filmato del controller lettore al punto di vista. Inoltre, non dimenticare di aggiungere MediaPlayer.framework per la vostra destinazione.
Ecco alcuni esempi di codice:
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *moviePlayerController;
}
@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Instantiate a movie player controller and add it to your view
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayerController.view setFrame:self.movieView.bounds]; // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
// Configure the movie player controller
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController prepareToPlay];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Start the movie
[moviePlayerController play];
}
@end
Swift
Si tratta di un autonomo progetto in modo che si può vedere tutto nel contesto.
Layout
Creare un layout simile alla seguente con un UIView
e UIButton
. Il UIView
sarà il contenitore in cui giocheremo il nostro video.
Aggiungi un video per il progetto
Se avete bisogno di un video di esempio di praticare con, è possibile ottenere uno da sample-videos.com . Sto utilizzando un video in formato mp4 in questo esempio. Trascinare e rilasciare il file video nel progetto. Ho anche dovuto aggiungere esplicitamente nelle risorse del bundle (vai a fasi di creazione> Copia Bundle Risorse , vedi questo rispondere per più).
Codice
Ecco il codice completo per il progetto.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Note
- Se avete intenzione di essere il passaggio dentro e fuori diversi video, è possibile utilizzare
AVPlayerItem
. - Se si utilizzano solo
AVFoundation
eAVPlayer
, allora devi costruire tutti i propri controlli. Se si desidera che la riproduzione di video a schermo intero, è possibile utilizzareAVPlayerViewController
. Sarà necessario importareAVKit
per questo. Viene fornito con un set completo di controlli per mettere in pausa, avanti veloce, indietro, stop, ecc Qui e qui sono alcuni tutorial video. -
MPMoviePlayerController
che potreste aver visto in altre risposte è deprecato.
Risultato
Il progetto dovrebbe assomigliare a questa ora.
NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];
[self presentMoviePlayerViewControllerAnimated:playerv];
NSURL *url = [NSURL URLWithString:[exreciesDescription objectForKey:@"exercise_url"]];
moviePlayer =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonClicked) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[moviePlayer view] setFrame: [self.view bounds]]; // frame must match parent view
[self.view addSubview: [moviePlayer view]];
[moviePlayer play];
-(void)playMediaFinished:(NSNotification*)theNotification
{
moviePlayer=[theNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
[moviePlayer.view removeFromSuperview];
}
-(void)doneButtonClicked
{
[moviePlayer stop];
[moviePlayer.view removeFromSuperview];
[self.navigationController popViewControllerAnimated:YES];//no need this if you are opening the player in same screen;
}
Versione Swift:
import AVFoundation
func playVideo(url: URL) {
let player = AVPlayer(url: url)
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
layer.backgroundColor = UIColor.white.cgColor
layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
layer.videoGravity = .resizeAspectFill
self.view.layer.addSublayer(layer)
player.play()
}
Utilizzare il seguente metodo.
self.imageView_VedioContainer
è la vista del contenitore del AVPlayer
.
- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
URLForResource:@"VID"
withExtension:@"3gp"]];
[playerViewController.player play];
playerViewController.showsPlaybackControls =YES;
playerViewController.view.frame=self.imageView_VedioContainer.bounds;
[playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line
[self.imageView_VedioContainer addSubview: playerViewController.view];
}
Non è possibile riprodurre un video all'interno di una vista. Deve essere giocato a schermo intero.