[英]How to add AVPlayerViewController to AVPlayerLayer in ios?
This is my code, how to add this AVPlayerViewController to AVPlayerLayer and how to hide that layer if we click hideButton. 这是我的代码,如何将这个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];
If you want to play Video in layer, then not required to add AVPlayerController. 如果要在图层中播放视频,则不需要添加AVPlayerController。
The code will be like: 代码如下:
Declare this 2 variable at start: 在开始时声明此2变量:
AVPlayer *player;
AVPlayerLayer *playerLayer;
Add following method, and call it at viewDidLoad
添加以下方法,并在
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
}
Whenever you want to start video playing, call this method: [player play]
, whenever you want to hide the layer, just hide the player layer and call [player pause]
to stop player playing the video. 每当您要开始播放视频时,请调用此方法:
[player play]
,只要要隐藏该图层,只需隐藏播放器图层并调用[player pause]
即可停止播放器播放视频。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.