您如何在swift 4中成功流式传输远程mp3文件?

时间:2019-03-24 19:14:54

标签: swift avfoundation nsurl

我正在使用swift 4,但无法成功将mp3文件流式传输到我的设备。没有错误可以带我到任何地方。就AVPlayers功能而言,我缺少什么?似乎其他人已经成功地传输了远程mp3文件。此外,服务器为https。

let newUrl = NSURL(string: urlMain)
let test = AVPlayer(url: newUrl as! URL)
test.play()

1 个答案:

答案 0 :(得分:0)

在您的类内部创建AVPlayer变量。

let player: AVPlayer = AVPlayer()

然后创建AVPlayerItem并将其设置为player。

func prepareToPlayAudio() {
    let url = newUrl
    asset = AVAsset(url: url)

    let assetKeys = ["playable", "hasProtectedContent"]

    playerItem = AVPlayerItem(asset: asset,
                              automaticallyLoadedAssetKeys: assetKeys)

    playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext)

    player = AVPlayer(playerItem: playerItem)
}

然后添加观察者以跟踪播放项目的状态。

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard context == &playerItemContext else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        return
    }

    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItemStatus

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

        switch status {
        case .readyToPlay:
        // Ready to play.
        case .failed:
        // Player item error.
        case .unknown:
            // Item is not ready.
        }
    }
}