Question about Audio Streaming


#1

Hi Ben, first off, thanks again for continuing to produce great tutorials on your site. I’ve benefited a lot from them, and I hope you continue the good work!

I wanted to ask if you could do a tutorial on streaming audio in iOS? You did a series on downloading large files, but I’m trying to figure out how to stream recorded audio from the server (not live streaming). Unfortunately, I haven’t found anything too comprehensive on streaming mp3’s in iOS so if you could perhaps do a tutorial on something like that, I would appreciate it. Just a suggestion!

Take care.
Sincerely;
Fayyaz


#2

Hi Fayyaz,

Thanks!

Audio (and video) streaming would be a great topic to cover. I’ll keep it in mind as I plan new episodes.

The short answer to your question is that streaming MP3s (or AACs) is essentially downloading the file progressively and feeding that data to a player as it is downloading.

You may have looked at AVAudioPlayer, but that class really just wants to work with local resources. To stream audio files from remote URLs, use AVPlayer. It looks like this:

let player = AVPlayer(url: urlToResource)
player.play()

This will handle all of the buffering for you silently and you have basically no control or feedback over how it is working. I recommend to drop down to AVURLAsset and AVPlayerItem so you can observe the properties and know more about when things are downloading, when it is ready to play, etc.

let asset = AVURLAsset(url: urlToResource)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)

There’s a ton of power in these APIs, so definitely read the docs.

Lastly, I want to mention that HTTP Live Streaming is not just for “live” content. It’s more about HTTP Streaming than it is about “Live”. I use HTTP Live Streaming (with encryption) to serve up video to the iOS and tvOS apps for NSScreencast. It works really well, but takes a little time to set it all up.

https://developer.apple.com/streaming/

Hope this helps!

– Ben