Search code examples
objective-ciosavplayerhttp-live-streaminglive-streaming

iOS: Live Streaming AVPlayer


I wanted to stream a song from a server, which seems to work just fine with the way that I have done it, but there are some things that don't seem possible with this approach.

I've currently instantiated an AVPlayer

player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:@"http://media.soundcloud.com/stream/songID?stream_token=myToken"]];

And called play on it when my application deems the buffer to be sufficient.

This plays the sound perfectly fine, but I'm finding that if I stop pointing to the AVPlayer instance, the player stops and if I push the application to the background, the sound fades and pauses until the application comes back to the foreground.

Is it possible to have the song keep playing in the background with AVPlayer?

If not, should I be looking at HTTP Live Streaming instead?

I'm very new to this side of iOS and I would greatly appreciate any guidance my fellow SO-ers can give me!


Solution

  • You should explicitly enable your app to play audio in the background. Insert the following key into the Info.plist file:

    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
    </array>
    

    (reference)

    Also add the following line before you start playing the audio:

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
    

    (reference)