【问题标题】:Swift: GET request with application/octet-stream in responseSwift:使用应用程序/八位字节流响应的 GET 请求
【发布时间】:2020-01-17 18:37:57
【问题描述】:

我有以下GET 请求(用于解释的简短版本)来播放声音:

func playSound() {

        guard let url = URL(string: "https://someWebsite/api/sounds/play?id=1") else {fatalError() }

        var request = URLRequest(url: url)

        request.httpMethod = "GET"

        request.setValue(uuid, forHTTPHeaderField: "X-AUTH-Device")
        request.setValue(appid, forHTTPHeaderField: "X-AUTH-AppID")
        request.setValue(someToken, forHTTPHeaderField: "X-AUTH-Token")

        URLSession.shared.dataTask(with: request) { data, response, _ in
            guard let httpResponse = response as? HTTPURLResponse,
                (200...599).contains(httpResponse.statusCode),
                let mediaData = data else {
                    return
            }
            print(mediaData)
        }
        .resume()
}

在此,在mediaData 中,我收到了一些数据,我只知道它必须是(Content-Type: application/octet-stream) 类型的流。所以我一直在理解如何解码/处理这些媒体数据以在 AVPlayer 或其他播放器中播放。 另外,我尝试在没有获取请求的情况下在 AVPlayer 中添加 URL 和标头,但它不起作用,我不确定在这里使用什么方法。提前感谢您的帮助!

【问题讨论】:

  • NSSound(data):传递任意Data对象,如果是合法的声音文件,就会得到一个NSSound对象。什么格式并不重要。

标签: swift audio avplayer


【解决方案1】:

这对我有用: https://github.com/neekeetab/CachingPlayerItem

在代码中:

   ...URLSession.shared.dataTask(with: request) { data, response, _ in
            guard let httpResponse = response as? HTTPURLResponse,
                (200...599).contains(httpResponse.statusCode),
                let mediaData = data else {
                    return
            }
            self.playSound(data: mediaData)
        }
        .resume()
}

func playSound(data: Data) {
    let playerItem = CachingPlayerItem.init(data: data, mimeType: "audio/mpeg", fileExtension: ".mp3")
    player = AVPlayer(playerItem: playerItem)
    guard let player = player else { return }
    player.play()
}

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 1970-01-01
    • 2018-08-16
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多