我正在使用 AVPlayer 在后台使用循环播放本地视频,视频播放正常,但在完成视频后需要暂停才能循环播放视频。我尝试了很多方法,也看到了很多关于堆栈溢出的帖子,但我没有找到合适的解决方案。我正在使用 Swift3。
代码在这里:
var videoplayer :AVPlayer = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "background4", ofType: "mp4")
videoplayer = AVPlayer(url: URL(fileURLWithPath: path!))
videoplayer.volume = 0
videoplayer.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
let playerLayer = AVPlayerLayer(player: videoplayer)
playerLayer.frame = self.view.frame
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
if (videoplayer.rate != 0) {
print("playing videoplayer")
self.blurBgImage.isHidden = true
}
playerLayer.zPosition = -1
videoplayer.rate = 0
videoplayer.play()
self.blurBgImage.layer.addSublayer(playerLayer)
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: videoplayer.currentItem, queue: nil, using: { (_) in
DispatchQueue.main.async {
let t1 = CMTimeMake(5, 100)
self.videoplayer.seek(to: t1)
self.videoplayer.play()
}
})
}
我也尝试过 AVPlayerLooper。
代码是:
var playerLooper: NSObject?
var playerLayer:AVPlayerLayer!
var queuePlayer: AVQueuePlayer?
func playVideo(_ filmName: String){
if let path = Bundle.main.path(forResource: filmName, ofType: "mp4") let url = URL(fileURLWithPath: path)
if #available(tvOS 10.0, *) {
let playerItem = AVPlayerItem(url: url as URL)
self.videoplayer = AVQueuePlayer(items: [playerItem])
self.playerLayer = AVPlayerLayer(player: self.videoplayer)
self.playerLooper = AVPlayerLooper(player: self.videoplayer as! AVQueuePlayer, templateItem: playerItem)
self.blurBgImage.layer.addSublayer(playerLayer!)
self.playerLayer?.frame = self.view.frame
self.videoplayer.volume = 10
self.videoplayer.play()
} else {
videoplayer = AVPlayer(url: url)
videoplayer.play()
loopVideo(videoplayer)
}
}
}
我应该怎么做才能无缝循环?提前致谢。
Best Answer-推荐答案 strong>
仅供引用,这里有示例代码:https://developer.apple.com/library/content/samplecode/avloopplayer/Introduction/Intro.html
@matt 删除的答案对我(在设备/模拟器上)适用于 iOS 10+ 设备:
Use AVPlayerLooper. That is exactly what it is for.
https://developer.apple.com/reference/avfoundation/avplayerlooper
Basically it implements AVQueuePlayer for you, constantly updating the
queue so that it never ends.
它无缝循环,没有任何白/黑光点。
例如
private var looper: AVPlayerLooper?
...
let queuePlayer = AVQueuePlayer(playerItem: item)
looper = AVPlayerLooper(player: queuePlayer, templateItem: item)
videoPlayerLayer.player = queuePlayer
如果您最终在可重复使用的单元格(例如 UICollectionView )中执行此操作,请确保在重复使用单元格之前禁用循环,否则您会遇到一些难以理解的崩溃:
looper?.disableLooping()
关于ios - 使用 AVPlayer-Swift 无缝循环播放视频,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/42105431/
|