在像GIF一样循环播放的UIView中自动播放MP4视频?

时间:2019-01-26 17:35:24

标签: ios swift xcode user-interface video

一旦用户转到该特定页面,我希望视频立即在没有控件的UIView内部开始播放。它将像gif一样循环播放。这是我在github上找到的代码,它似乎不起作用。当我拉起页面时,它仅显示白色的UIView。我的文件名也正确。

import Foundation
import UIKit
import AVKit
import AVFoundation

class RampWallPush: UIViewController {

@IBOutlet weak var videoView: UIView!

var player: AVPlayer?

override func viewDidLoad() {
    super.viewDidLoad()

    // Load video resource
    if let videoUrl = Bundle.main.url(forResource: "small", withExtension: "mp4") {

        // Init video
        self.player = AVPlayer(url: videoUrl)
        self.player?.isMuted = true
        self.player?.actionAtItemEnd = .none

        // Add player layer
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        playerLayer.frame = view.frame

        // Add video layer
        self.videoView.layer.addSublayer(playerLayer)

        // Play video
        self.player?.play()

        // Observe end
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
    }
}

// MARK: - Loop video when ended.
@objc func playerItemDidReachEnd(notification: NSNotification) {
    self.player?.seek(to: CMTime.zero)
    self.player?.play()
}

}

1 个答案:

答案 0 :(得分:1)

您的代码有效,您需要验证文件是否存在于项目中以及.......

    // Load video resource
  if let videoUrl = Bundle.main.url(forResource: "sample", withExtension: "mp4") {
        // exists
  }
  else {

     print("NoFile")
  }

因此选择文件,然后

enter image description here


您需要更改框架

 playerLayer.frame = CGRect(x:0,y:0,width:200,height:300) 
 self.videoView.layer.addSublayer(playerLayer)
 playerLayer.center = videoView.center 

创建了一个演示Here