This is my code, how to add this AVPlayerViewController to AVPlayerLayer and how to hide that layer if we click 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.
The code will be like:
Declare this 2 variable at start:
AVPlayer *player;
AVPlayerLayer *playerLayer;
Add following method, and call it at 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.