这是我的代码,如何将此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];
答案 0 :(得分:0)
如果你想在图层中播放视频,则不需要添加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]
即可停止播放视频的播放器。