[英]Sync video in AVPlayerLayer and AVPlayerViewController
[英]How to add AVPlayerViewController to AVPlayerLayer in ios?
這是我的代碼,如何將這個AVPlayerViewController添加到AVPlayerLayer,以及如何在單擊hideButton時隱藏該層。
NSString *videoFilePath = [[NSBundle mainBundle]pathForResource:self.string ofType:@"mp3"];
self.avPlayer = [[AVPlayer alloc]initWithURL:[NSURL fileURLWithPath:videoFilePath]];
self.avPlayerViewController = [[AVPlayerViewController alloc]init];
self.avPlayerViewController.view.frame = CGRectMake(25,375,250,300);
self.avPlayerViewController.player = self.avPlayer;
[self.view addSubview:self.avPlayerViewController.view];
[self.avPlayerViewController.player play];
如果要在圖層中播放視頻,則不需要添加AVPlayerController。
代碼如下:
在開始時聲明此2變量:
AVPlayer *player;
AVPlayerLayer *playerLayer;
添加以下方法,並在viewDidLoad
調用它
-(void)setUpVideoPlayer
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *aErr;
[audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&aErr];
NSString *videoFilePath = [[NSBundle mainBundle] pathForResource:@"videoFileName" ofType:@"videoFileType"];
NSURL *fileURL = [NSURL fileURLWithPath:videoFilePath];
player = [AVPlayer playerWithURL:fileURL];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[playerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
playerLayer.frame = // Set Frame whichever you want;
[self.videoView.layer addSublayer:playerLayer];
[player seekToTime:kCMTimeZero];
[player setVolume:0.0f];
[player setActionAtItemEnd:AVPlayerActionAtItemEndNone];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[player currentItem]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerStartPlaying)
name:UIApplicationDidBecomeActiveNotification object:nil];
}
-(void)playerStartPlaying
{
[player play];
}
-(void)playerItemDidReachEnd:(NSNotification*)notification
{
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero]; // Play it again when video ends
}
每當您要開始播放視頻時,請調用此方法: [player play]
,只要要隱藏該圖層,只需隱藏播放器圖層並調用[player pause]
即可停止播放器播放視頻。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.