defining view frame size for AV Player ViewControl

2020-07-22 09:24发布

How does one play a video as a background in iOS? I followed this question How to play a local video with Swift?, but AV Player ViewController is a controller and doesn't let me decide where and how big the view containing video is. It always takes some predefined values.

1条回答
迷人小祖宗
2楼-- · 2020-07-22 09:55

I've got this working for a project that I've done but not with an AVPlayerViewController - just a plain AVPlayer that I add to a view's layer. I have a collection view but you can just insert the video on a layer wherever you want. Try something like this:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"my_local_file" ofType:@"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
self.avPlayerItem = [AVPlayerItem playerItemWithURL:fileURL];
self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.avPlayerLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:self.avPlayerLayer below:self.collectionView.layer];
// could also try [self.view.layer insertSublayer:self.avPlayerLayer atIndex:0];
[self.avPlayer play];

Basically, set the AVPlayerLayer.frame to the size that you want.

查看更多
登录 后发表回答