AVPlayer pathForResource 没有被调用

AVPlayer pathForResource not getting called

我有应用程序欢迎屏幕的视频背景,但是当我 运行 时只出现一个空白屏幕。

资源部分的包路径字符串完全正确,所以拼写错误不是问题或任何问题。当我在 "if path" 块上放置断点时,虽然它没有被调用。这是在视图中加载并且 "AVKit" 和 "AVFoundation" 都被导入并且没有错误。

有什么见解吗?谢谢!

    let moviePath = NSBundle.mainBundle().pathForResource("Ilmatic_Wearables", ofType: "mp4")

    if let path = moviePath {

        let url = NSURL.fileURLWithPath(path)
        let player = AVPlayer(URL: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.view.frame = self.view.bounds
        self.view.addSubview(playerViewController.view)
        self.addChildViewController(playerViewController)
        player.play()
    }

很奇怪,如果 moviePath 不是你所说的 nil,你的代码应该可以工作。以这种方式检查:

if let moviePath != nil {
       ...
}

更新

检查您的视频文件的 Target Membership 是否已设置

编辑 (11/13/2015) - 试试这个:

右键单击,从项目导航器中删除视频文件,select移至回收站。

然后将视频从 finder 拖回项目导航器。

选择添加这些文件的选项时:

  • 如果需要请勾选复制项目
  • 检查添加到目标

重新构建您的项目,看看它现在是否有效!

我提供了适合我的示例代码:

import AVFoundation
import AVKit

class ExampleViewController: UIViewController {
    
    func loadAndPlayFile() {
        
        guard let path = NSBundle.mainBundle().pathForResource("filename", ofType: "mp4") else {
            print("Error: Could not locate video resource")
            return
        }
        
        let url = NSURL(fileURLWithPath: path)
        let moviePlayer = AVPlayer(URL: url)
        let moviePlayerController = AVPlayerViewController()
        moviePlayerController.player = moviePlayer
        
        presentViewController(moviePlayerController, animated: true) {
            moviePlayerController.player?.play()
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        loadAndPlayFile()
    }
}

/编辑


检查视频文件是否在 iTunes 中播放。如果它在 iTunes 中播放,它也应该在 iOS 模拟器和设备上播放。

如果它不能在 iTunes 中播放,但可以与 VLC 媒体播放器、Quicktime 等一起使用,则需要重新编码。

iOS supports many industry-standard video formats and compression standards, including the following:

H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48 kHz, stereo audio in .m4v, .mp4, and .mov file formats H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48 kHz, stereo audio in .m4v, .mp4, and .mov file formats MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48 kHz, stereo audio in .m4v, .mp4, and .mov file formats Numerous audio formats, including the ones listed in Audio Technologies