使用Avplayer / kit问题播放本地视频

时间:2017-02-21 20:58:00

标签: ios swift xcode avplayer

每当我运行该项目时,它都会启动视频播放器,但视频无法播放  (the code and error)。 我该如何解决?如果图片中的代码不够清晰,则代码如下:

import UIKit
import AVKit
import AVFoundation


class ViewController: UIViewController {

    let avPlayerViewController = AVPlayerViewController()
    var avPlayer:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from nib.

        let urlPathString = Bundle.main.path(forResource: "small", ofType: "mp4")

        if urlPathString != nil {

            let movieUrl = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")

            self.avPlayer = AVPlayer(url: movieUrl as URL)
            self.avPlayerViewController.player = self.avPlayer

        }
    }



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


    @IBAction func playButtonTapped(_ sender: AnyObject) {
        //Trigger the video to play
        self.present(self.avPlayerViewController, animated: true) { () -> Void in self.avPlayerViewController.player?.play()    }


    }

}

2 个答案:

答案 0 :(得分:1)

评论中提出的解决方案和@Guan回答的解决方案都是正确的。

你的urlPathString实际上是零,

使其有效 -

  

1-按照评论和上面的答案或

的建议添加目标会员资格

执行以下操作

  

1.1-从包中删除small.mp4,确保move it to trash

     

2.1 - 转到垃圾箱并再次将你的mp4文件拖放到项目中,你会得到一个这样的窗口 -   Window on drag and drop

在添加它的同时确保你 -

  

检查projectTarget复选框,如下面的屏幕截图所示 -

     

Checked box for app target

确保文件名为small.mp4

答案 1 :(得分:0)

确保您的urlPathString不是零。 我不知道下面的代码是什么意思:

let movieUrl = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")

我认为模拟器无法获取mac中的文件路径。(我不确定,我之前没有这样做)。 您可以检查文件的目标成员资格。

enter image description here

代码可以这样工作:

var urlPaht = Bundle.main.url(forResource: "small", withExtension:"mp4")
if urlPaht == nil {
        urlPaht = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")
}
self.avPlayer = AVPlayer(url: movieUrl as URL)
self.avPlayerViewController.player = self.avPlayer