有没有一种相对简单的方法可以在 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)
}
}
关于ios - 使用 AVFoundation AVPlayer 循环播放视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5361145/