Fritz Menzer
Fritz Menzer

Reputation: 123

iOS background audio stops when screen is locked

I'm trying to get my audio app to play in the background. So far I added "app plays audio" to the "required background modes" in info.plist and also the following code just before starting my sound generator:

AudioSessionInitialize(NULL, kCFRunLoopDefaultMode, &interruptionListener, sgD);
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, &routeChangeListener, sgD);

// select "Playback" audio session category
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];

OSStatus propertySetError = 0;
UInt32 category = kAudioSessionCategory_MediaPlayback; 
propertySetError = AudioSessionSetProperty ( kAudioSessionProperty_AudioCategory, sizeof (category), &category );

AudioSessionSetActive(true);

However, this works only when I switch to another app or to the iPod's main screen. When I turn off the screen, it also turns off my audio output, which is definitely not what I want. However, all tutorials / documentation / answers to questions on stackoverflow seem to indicate that keeping the audio running while the screen is off comes automatically when you get the background audio to work. Does anybody have a hint for me? Thanks a lot in advance! Fritz

Upvotes: 9

Views: 4073

Answers (2)

Paul Slocum
Paul Slocum

Reputation: 1644

Old question, but I'm having the same problem, and I couldn't find other related questions or answers. No matter how I configured my AudioQueue callback, I couldn't get it to consistently go into the background without having audio dropouts. If I made the buffers huge, then it was almost working consistently, but with giant buffers the audio response delay for the UI was excessively long.

The only solution I found that worked was to switch from AudioQueue to Audio Units (RemoteIO) for my callback, and unlike what is stated in the previous solution here, I didn't find that it was necessary to set the Audio Unit buffer size to 4096. I still get a very small dropout when the app goes into the background if it's attached to the debugger, but when the app is running normally without the debugger then I don't get any dropouts.

Upvotes: 0

Frank Krueger
Frank Krueger

Reputation: 71053

This article explains the problem:

Technical Q&A QA1606 Audio Unit Processing Graph - Ensuring audio playback continues when screen is locked

Basically, you just need to make sure you set all AudioUnits to support 4096 slices:

// set the mixer unit to handle 4096 samples per slice since we want to keep rendering during screen lock
UInt32 maxFPS = 4096;
AudioUnitSetProperty(
    mMixer,
    kAudioUnitProperty_MaximumFramesPerSlice,
    kAudioUnitScope_Global,
    0,
    &maxFPS,
    sizeof(maxFPS));

Upvotes: 5

Related Questions