迅速
这是一个独立的项目,因此您可以在上下文中查看所有内容。
布局
使用 aUIView
和 a创建如下布局UIButton
。将UIView
是我们将在其中播放视频的容器。
将视频添加到项目中
如果您需要一个示例视频来练习,您可以从sample-videos.com获得一个。在此示例中,我使用的是 mp4 格式的视频。将视频文件拖放到您的项目中。我还必须将它显式添加到捆绑资源中(转到Build Phases > Copy Bundle Resources,有关更多信息,请参阅此答案)。
代码
这是该项目的完整代码。
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
笔记
结果
该项目现在应该是这样的。