使用 AVFoundation AVPlayer 循环播放视频? [英] Looping a video with AVFoundation AVPlayer?

查看:27
本文介绍了使用 AVFoundation AVPlayer 循环播放视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AVFoundation 中是否有一种相对简单的方法来循环播放视频?

Is there a relatively easy way of looping a video in AVFoundation?

我已经像这样创建了我的 AVPlayer 和 AVPlayerLayer:

I've created my AVPlayer and AVPlayerLayer like so:

avPlayer = [[AVPlayer playerWithURL:videoUrl] retain];
avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];

avPlayerLayer.frame = contentView.layer.bounds;
[contentView.layer addSublayer: avPlayerLayer];

然后我播放我的视频:

[avPlayer play];

视频播放正常,但在结尾处停止.使用 MPMoviePlayerController,您只需将其 repeatMode 属性设置为正确的值.AVPlayer 上似乎没有类似的属性.似乎也没有回调会告诉我电影何时结束,这样我就可以找到开头并再次播放.

The video plays fine but stops at the end. With the MPMoviePlayerController all you have to do is set its repeatMode property to the right value. There doesn't appear to be a similar property on AVPlayer. There also doesn't seem to be a callback that will tell me when the movie has finished so I can seek to the beginning and play it again.

我没有使用 MPMoviePlayerController,因为它有一些严重的限制.我希望能够一次播放多个视频流.

I'm not using MPMoviePlayerController because it has some serious limitations. I want to be able to play back multiple video streams at once.

推荐答案

您可以在播放器结束时收到通知.检查 AVPlayerItemDidPlayToEndTimeNotification

You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification

设置播放器时:

对象

  avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(playerItemDidReachEnd:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:[avPlayer currentItem]];

这将防止播放器在最后暂停.

this will prevent the player to pause at the end.

在通知中:

- (void)playerItemDidReachEnd:(NSNotification *)notification {
    AVPlayerItem *p = [notification object];
    [p seekToTime:kCMTimeZero];
}

这将倒带电影.

不要忘记在释放播放器时取消注册通知.

Don't forget un unregister the notification when releasing the player.

迅捷

avPlayer?.actionAtItemEnd = .none

NotificationCenter.default.addObserver(self,
                                       selector: #selector(playerItemDidReachEnd(notification:)),
                                       name: .AVPlayerItemDidPlayToEndTime,
                                       object: avPlayer?.currentItem)

@objc func playerItemDidReachEnd(notification: Notification) {
    if let playerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: kCMTimeZero)
    }
}

Swift 4+

@objc func playerItemDidReachEnd(notification: Notification) {
    if let playerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: CMTime.zero, completionHandler: nil)
    }
}

这篇关于使用 AVFoundation AVPlayer 循环播放视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆