2
votes

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!

2

2 Answers

8
votes

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)

0
votes

Technical Q&A QA1668 Playing media while in the background using AV Foundation on iOS

Q: How do I ensure my media will continue playing when using AV Foundation while my application is in the background?

A: You must declare your app plays audible content while in the background, and assign an appropriate category to your audio session. See also Special Considerations for Video Media.

Declare your app plays Audible Content while in the Background

First, declare your application provides specific background services and must be allowed to continue running while in the background. To do this, add the UIBackgroundModes key in your app's Info.plist file. Its value is an array that contains one or more strings that identify which background tasks your application supports. Specify the string value audio to indicate the application plays audible content to the user while in the background:

Figure 1 Declaring the app plays audible content in the background.

Important: The UIBackgroundModes audio key will also allow apps to stream media content in the background using AirPlay (see also Special Considerations for Video Media).