使用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];
}
这将倒回电影。
在释放播放器时不要忘记取消注册通知。
迅速
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: Notification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer?.currentItem)
@objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: kCMTimeZero, completionHandler: nil)
}
}
如果有帮助,在iOS / tvOS 10中,有一个新的AVPlayerLooper(),您可以使用它来创建无缝循环视频(Swift):
player = AVQueuePlayer()
playerLayer = AVPlayerLayer(player: player)
playerItem = AVPLayerItem(url: videoURL)
playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
player.play()
这是在WWDC 2016的“AV基础播放进展”中发布的:https://developer.apple.com/videos/play/wwdc2016/503/
即使使用这些代码,在我向Apple提交错误报告并得到以下回应之前,我还是有一个呃逆:
具有比音频/视频轨道长的电影持续时间的电影文件是问题。 FigPlayer_File禁用无间隙转换,因为音轨编辑比电影持续时间短(15.682 vs 15.787)。
您需要修复电影文件以使电影持续时间和音轨持续时间相同,或者您可以使用AVPlayerLooper的时间范围参数(设置时间范围从0到音轨的持续时间)
事实证明,Premiere一直在导出文件的音频轨道与视频长度略有不同。 在我的情况下,完全删除音频并很好解决了问题。
在Swift中 :
当玩家结束时,你可以得到一个通知...检查AVPlayerItemDidPlayToEndTimeNotification
设置播放器时:
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.None
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "playerItemDidReachEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: avPlayer.currentItem)
这会阻止玩家在最后暂停。
在通知中:
func playerItemDidReachEnd(notification: NSNotification) {
if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
playerItem.seekToTime(kCMTimeZero)
}
}
Swift3
NotificationCenter.default.addObserver(self,
selector: #selector(PlaylistViewController.playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer?.currentItem)
这将倒回电影。
在释放播放器时不要忘记取消注册通知。
链接地址: http://www.djcxy.com/p/56873.html