如何使用AVPlayer播放数据类型的视频?

时间:2018-07-04 11:13:31

标签: ios swift avplayer

使用以下代码从远程下载后,我尝试播放视频。

let player = AVPlayer(url: URL(dataRepresentation: VideoService.instance.videoInfoArray[0].video, relativeTo: nil)!)
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}

我的VideoService类是单例类,视频变量类型是Data()。但是,当我尝试使用以下代码播放视频时,它不起作用。如何使用数据代表播放视频?

1 个答案:

答案 0 :(得分:1)

根据URL class documentation,初始化程序init?(dataRepresentation:relativeTo:isAbsolute:)采用Data参数,是的,但是该数据应该是 URL字符串的ASCII表示,而不是您要播放的实际数据。

您需要做的是将视频数据保存到文件中,并使用文件的URL初始化AVPlayer

guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)?.first else { return }
url.appendPathComponent("video.mpeg") // or whatever extension the video is
VideoService.instance.videoInfoArray[0].video.write(to: url) // assuming video is of Data type
let player = AVPlayer(url: url)
// other stuff with the player

要确定播放器无法播放文件的原因,请使用key-value observing of player's status property。如果您发现AVPlayer.Status.failed发生了变化,则可以检查播放器的error属性以查看本地化的原因和错误代码。

var playerStatusContext = 0
player.addObserver(player, forKeyPath: "status", options: [.new, .initial], context: &playerStatusContext)

// (...)

override func observeValue(forKeyPath keyPath: String?,
                       of object: Any?,
                       change: [NSKeyValueChangeKey : Any]?,
                       context: UnsafeMutableRawPointer?) {

    // Only handle observations for the playerItemContext
    guard context == &playerStatusContext else {
        super.observeValue(forKeyPath: keyPath,
                           of: object,
                           change: change,
                           context: context)
        return
    }

    if keyPath == #keyPath(AVPlayer.status) {
        let status: AVPlayer.Status
        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayer.Status(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }

        if status == .failed {
            print(player.error)
        }
    }
}