我正在尝试将视频添加为背景,但它不起作用。
这是我正在使用的代码:
import UIKit
import MediaPlayer
import AVFoundation
import AVKit
import MediaPlayer
class WelcomeViewController: UIViewController {
let moviePlayerController = AVPlayerViewController()
var aPlayer = AVPlayer()
func playBackgroundMovie(){
if let url = NSBundle.mainBundle().URLForResource("WelcomeVideo", withExtension: "mp4") {
aPlayer = AVPlayer(URL: url)
}
moviePlayerController.player = aPlayer
moviePlayerController.view.frame = view.frame
moviePlayerController.videoGravity = AVLayerVideoGravityResizeAspectFill
moviePlayerController.view.sizeToFit()
moviePlayerController.videoGravity = AVLayerVideoGravityResizeAspect
moviePlayerController.showsPlaybackControls = false
moviePlayerController.view.userInteractionEnabled = false
aPlayer.play()
view.insertSubview(moviePlayerController.view, atIndex: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.moviePlayerController.view.backgroundColor = UIColor.grayColor()
playBackgroundMovie()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didPlayToEndTime", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didPlayToEndTime(){
aPlayer.seekToTime(CMTimeMakeWithSeconds(0, 1))
aPlayer.play()
}
}
当我运行我的应用程序时,它崩溃为行:
aPlayer = AVPlayer(URL: url!)
我添加了" WelcomeVideo.mp4"在我的项目中也是:
正如您在图片上看到的那样," WelcomeVideo.mp4"就在当前的视图控制器类旁边......我在这里做错了什么?
答案 0 :(得分:2)
修正了自己!忘了我必须将它添加到构建阶段中的复制捆绑包。
答案 1 :(得分:1)
if let filePath = Bundle.main.path(forResource: "small", ofType: ".mp4") {
let filePathURL = NSURL.fileURL(withPath: filePath)
let player = AVPlayer(url: filePathURL)
let playerController = AVPlayerViewController()
playerController.view.backgroundColor = UIColor.red
playerController.player = player
self.present(playerController, animated: true) {
player.play()
}
}