AVPlayer在视图中

BAR*_*ODE 3 objective-c ios avplayer

我试图在视图控制器上使用视频,但没有全屏显示,只有足够的空间放在顶部的标签和底部的按钮,这可能吗?如果不是我怎么能这样,如果用户跳过视频或它完成它转到某个viewController?

- (void)viewDidLoad {
    [super viewDidLoad];

NSURL *videoURL = [[NSBundle mainBundle]URLForResource:@"TTPlaneHits" withExtension:@"mp4"];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];


AVPlayer *player = [AVPlayer playerWithURL:videoURL];
playerLayer.frame = CGRectMake(0, 21, self.view.frame.size.width, self.view.frame.size.height - 45 - 21);
[self.view.layer addSublayer:playerLayer];
AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
controller.player = player;
[player play];


[self.view addSubview:controller.view];
controller.view.frame = self.view.frame;
Run Code Online (Sandbox Code Playgroud)

Kai*_*tis 8

来自Apple的文档:

您可以在AVPlayerLayer类的CoreAnimation层中显示由AVPlayer实例播放的项目的可视内容; 要将实时回放与其他CoreAnimation图层同步,您可以使用AVSynchronizedLayer.您不能将AVVideoCompositionCoreAnimationTool的实例与AVPlayer对象一起使用; 对于离线渲染,您应该使用AVAssetExportSession.

试试这个:

(playerView只是放在故事板中的UIView的IBOutlet)

 -(void)viewDidLoad {
    [super viewDidLoad];

    NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp4"]];

    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:videoURL];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:item];

    CALayer *superlayer = self.playerView.layer;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    [playerLayer setFrame:self.playerView.bounds];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [superlayer addSublayer:playerLayer];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];


    [player seekToTime:kCMTimeZero];
    [player play];

}

-(void)playerDidFinishPlaying:(NSNotification *)notification {

    [self performSegueWithIdentifier:@"YourIdentifier" sender:self];
}
Run Code Online (Sandbox Code Playgroud)


dan*_*mbr 8

Swift版本

func addVideoPlayer(videoUrl: URL, to view: UIView) {
    let player = AVPlayer(url: videoUrl)
    let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    layer.backgroundColor = UIColor.white.cgColor
    layer.frame = view.bounds
    layer.videoGravity = .resizeAspectFill
    view.layer.sublayers?
        .filter { $0 is AVPlayerLayer }
        .forEach { $0.removeFromSuperlayer() }
    view.layer.addSublayer(layer)
}
Run Code Online (Sandbox Code Playgroud)