ios - 使用 AVFoundation AVPlayer 循环播放视频?

有没有一种相对简单的方法可以在 AVFoundation 中循环播放视频?

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

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

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

然后我播放我的视频:

[avPlayer play];

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

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

最佳答案

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

设置播放器时:

ObjC

  avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

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

这将防止播放器在结束时暂停。

在通知中:

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

这将倒带电影。

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

swift

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)
    }
}

https://stackoverflow.com/questions/5361145/

相关文章:

iphone - 如何在 Objective-C 2.0 中将方法标记为已弃用?

ios - 较小时 UIScrollView 的中心内容

objective-c - "FOUNDATION_EXPORT"与 "extern"

iphone - 从实例中获取类的名称

ios - 如何设置一个简单的委托(delegate)来在两个 View Controller 之间

ios - UIView 隐藏/显示动画

objective-c - Swift References 中的 _ 下划线代表什么?

ios - 如何在 UITableView 中设置分隔符的全宽

ios - iPhone SDK : what is the difference between

objective-c - NSInvocation 傻瓜?