我正在使用AVFoundation
套件播放本地视频
我尝试了以下代码:
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: "Air Bike", ofType: "mov")
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()
}
}
我正在尝试几种不同的方法,但是仍然收到相同的错误消息,有人可以如何解决此问题?
答案 0 :(得分:0)
**use**
layer.frame = videoViewContainer.layer.bounds
代替
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
答案 1 :(得分:0)
func initializeVideoPlayerWithVideo() {
guard let path = Bundle.main.path(forResource: "jagdeep", ofType:".MOV") else {
debugPrint("video.m4v not found")
return
}
self.player = AVPlayer(url: URL(fileURLWithPath: path))
// 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)
player?.play()
}
“这里是我的视频名” jagdeep并键入.MOV ,它在我这边工作。这是您使用mov类型的代码中的问题。我只是将视频名称jagdeep.MOV拖到我的项目中,然后使用您的代码。还可以,
答案 2 :(得分:0)
谢谢您的回复,似乎找不到文件,这是我的项目的屏幕截图,这可能是视频位于我的主文件夹中的原因! Screenshot