How to convert the binary obtained from the server into a playable Data type?
Question
When I use URLSession, there are many examples,butI looked at the official example, didn't find how to convert the binary downloaded from the server into a data structure that can be used by AudioPlayer.
When I printed out audio_mpeg, I found that it is of type OpenAPIRuntime.HTTPBody.
How can I convert OpenAPIRuntime.HTTPBody type to be used by AudioPlayer?
Hi @koi646,
you turn an HTTPBody (a stream of byte chunks) into Data by accumulating it using this initializer: https://swiftpackageindex.com/apple/swift-openapi-runtime/1.4.0/documentation/openapiruntime/foundation/data/init(collecting:upto:)
So something like:
let audioData = Data(collecting: audio_mpeg, upTo: 10 * 1024 * 1024) // chose max of 10MB, adjust as needed
From this point on, converting the Data value to something compatible with AudioPlayer, the story is the same as when using URLSession directly. So for example: https://developer.apple.com/documentation/avfaudio/avaudioplayer/1388809-init
thx, I will give it a try.
Closing for now, please reopen if the suggested solution still didn't fix your issue.