Swift:GET 请求,响应为 application/octet-stream

Swift: GET request with application/octet-stream in response

我有以下 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) 类型的流。所以我一直在理解如何 decode/handle 这个媒体数据可以在 AVPlayer 或其他播放器中播放。 另外,我尝试在没有 get 请求的情况下在 AVPlayer 中添加 URL 和 headers 但它没有用,我不确定在这里使用什么方法。预先感谢您的帮助!

这对我有用: 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()
}