将本地文件添加到项目文件

时间:2016-06-02 08:59:35

标签: ios xcode swift video local

enter image description here导入UIKit     导入AVKit     导入AVFoundation

class ViewController: UIViewController {


var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()

@IBAction func playMusic(sender: AnyObject) {
    let fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/32134.mp4")
    playerview = AVPlayer(URL: fileURL)

    playerviewcontroller.player = playerview

    self.presentViewController(playerviewcontroller, animated: true){

        self.playerviewcontroller.player?.play()
    }


}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

当我使用该应用程序时它不起作用,因为该文件在我的Mac上。请有人解释我如何将视频文件放入项目中。感谢

2 个答案:

答案 0 :(得分:1)

您只需要将要在项目中静态使用的视频或图像拖放到文件中。我刚刚添加:

enter image description here

 @IBAction func playMusic(sender: AnyObject) {

        let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
        let fileURL = NSURL(fileURLWithPath: path)

        playerview = AVPlayer(URL: fileURL)

        playerviewcontroller.player = playerview

        self.presentViewController(playerviewcontroller, animated: true){

            self.playerviewcontroller.player?.play()
        }


    }

另一种方法是将您的视频,音频或图片文件放在项目文件夹中,如下所示:

enter image description here

之后,按照以下步骤将此文件添加到xcode项目中:

enter image description here

您将获得drapDown窗口并选择您的文件,如下所示:

enter image description here

您获取文件路径的代码相同:

 let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
 let fileURL = NSURL(fileURLWithPath: path)

答案 1 :(得分:0)

尝试检查nil。还可以从NSBundle

获取视频文件网址
if let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4") {
    let fileURL = NSURL(fileURLWithPath: path!)

    playerview = AVPlayer(URL: fileURL)

    playerviewcontroller.player = playerview

    self.presentViewController(playerviewcontroller, animated: true){

        self.playerviewcontroller.player?.play()
    }
   }