Is it possible/Is there a way to save an audio stream to a local file? I'm very inexperienced and I dont know where to start -- a point in the right direction would be appreciated.
I'm building an app that streams audio from URLs (eg http://audiostream.mp3). I'd like the user to be able to save audio, to a file, from when they start listening to when they finish. As the audio will be a stream, my concern is that i'm not dealing with a complete mp3 file -- i'm guessing this makes things trickier than simply downloading a complete mp3.
Thanks in advance for your help with this.
You can save the buffered song at the same time when it is played.
You can save live audio stream with indefinite duration. You need to use
ResourceLoader
andURlSessionDataTask
.It's a bit tricky process, so I will explain step by step:
Making an AVURLAsset:
Set the delegate:
Following delegate function will be called:
Now inside this function we will call a function to start the data request, so that downloading of sound buffer can start:
as you can see we have opened a output stream. We will use this stream to write buffer to our disk.
Now as we initiated a dataTask with the given URL, we will start receiving data bytes into the delegate function:
Now we have started receiving live audio stream. Last piece of the puzzle is to store the audio stream. It is the simplest part. We just create an OutputStream object, open it then append the bytes we are receiving in the above delegate function and thats it, we saved the desired part of the live audio stream.
Here is the source code that I wrote on a blog in Medium, solving the problem that you faced: https://github.com/pandey-mohan/LiveAudioCapture