背景视频循环不在swift工作

时间:2017-05-25 07:14:10

标签: ios swift swift3 avfoundation avplayer

我已经创建了页面控件,并且后台视频将被加载,视频正在播放但循环不起作用,我曾参考stackoverflow 但我不能得到正确的答案

这是我的代码:

 override func viewDidLoad() {
    super.viewDidLoad()
    self.pageController.currentPage = 0
    loadVideo(currentPage: 0)
 }

func loadVideo(currentPage: Int) {

    DispatchQueue.main.async {

    self.videoPath =  Bundle.main.url(forResource: "BoardVideoArray[currentPage]", withExtension: "mp4")

    self.player = AVPlayer(url: self.videoPath!)
    self.player?.actionAtItemEnd = .none
    self.player?.isMuted = true

   self.playerLayer = AVPlayerLayer(player: self.player)
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.playerLayer.zPosition = -1
    }

    playerLayer.frame = videoVIew.frame

     videoVIew.layer.addSublayer(playerLayer)
     videoVIew.bringSubview(toFront: pageController)

    player?.play()

    //loop video
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: nil, using: { (_) in
        DispatchQueue.main.async {
            self.player?.seek(to: kCMTimeZero)
            self.player = AVPlayer(url: self.videoPath!)
            self.player.play()
        }
    })

}

我宣布玩家和avplayerLayer超出范围

   var player: AVPlayer!
   var playerLayer = AVPlayerLayer()

我花了4个多小时,但我找不到我犯的错误。 问题是视频没有进行循环

2 个答案:

答案 0 :(得分:0)

试试这种方式。

    guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
        debugPrint("video.m4v not found")
        return
    }
    //VideoPlayer is a subClass of AVPlayer
    let player = VideoPlayer(url: URL(fileURLWithPath: path))
    playerViewController = AVPlayerViewController()
    playerViewController.videoGravity = AVLayerVideoGravityResizeAspectFill
    playerViewController.player = player
    //self.videoPlayerView is a UIView in which i want to show video.
    playerViewController.view.frame = self.videoPlayerView.bounds
    self.videoPlayerView.addSubview(playerViewController.view)
    playerViewController.showsPlaybackControls = false
    playerViewController.player?.play()
    player.shouldMute(mute: true)
    NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.videoDidStopPlaying(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)


func videoDidStopPlaying(notification:Notification) {
        self.playerViewController.player?.seek(to: kCMTimeZero)
        self.playerViewController.player?.play()
    }

答案 1 :(得分:0)

我编写了一个名为UIView的Swift SDLoopingVideoView子类,该子类播放并循环播放任何兼容的AVPlayer视频文件并自动缩放以填充视图。它可以完全在Interface Builder中设置。它作为视频背景非常有用,您无需担心视频循环,因为它是自动管理的。您可以在Github上找到它:SDLoopingVideoView