Play data while downloading

152 Views Asked by At

I am trying do play songs from soundcloud, which is working fine for one exception: when the response handler is called, the download of the file is allready complete. I'd like to start playing the file directly after the download started, but i have no clue how to access the data before the response handler gets called. Accessing the data ln the progress handler would be nice, but i need a hint on how to do it.

2

There are 2 best solutions below

1
On

I suggest you at least two options to perform what you want:
1. AVPlayer supports playing a file from http. If you download a static file - you can just ask a player to stream over http.
2. You can download a small chunks of file (5 MB at once, for example) and append them to the result file or write directly into memory buffer. You can download a file chunk of specified size by just adding a Content-Range header with an offset you need. (see RFC, 14.16 Content-Range for more specific info). This method requires server to support partial downloads, but in nowadays it is harder to find a sever that does not support this =) Alamofire easily allows you to do that.

2
On

If you write your own download code using NSURLConnection and initWithRequest:delegate:startImmediately:, the delegate methods (e.g. connection:didReceiveData:) will be called as the data becomes available.

You risk running out of data if you try to play the sound as it is downloaded. You should probably implement a buffering system where you download enough extra data for several seconds of playback before you start playing. That way you can smooth over short "stutters" in the download.