我正在使用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()
}
}
我正在尝试一些不同的方法,我仍然得到相同的错误消息,有人如何解决这个问题?
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拖到我的项目中并使用您的代码。它的确定
**use**
layer.frame = videoViewContainer.layer.bounds
代替
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
感谢您的回复,好像在这里找不到文件是我的项目的截图,这可能是视频在我的主文件夹中的原因! Screenshot