ikanimo
ikanimo

Reputation: 491

AVAudioPlayer background task is not working [iOS]

I have tried everything:

-setup info.plist Required background modes : App plays audio;

-setup player:

 [[AVAudioSession sharedInstance] setDelegate: self];

// allow app continue to play when the screen is locked
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                       error:nil];

UInt32 doSetProperty = 0;
AudioSessionSetProperty ( kAudioSessionProperty_OverrideCategoryMixWithOthers,
                         sizeof (doSetProperty),
                         &doSetProperty
                         );

// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
                                 kAudioSessionProperty_AudioRouteChange,
                                 audioRouteChangeListenerCallback,
                                 self
                                 );

// Activates the audio session.

NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];

[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

What am I forgetting? Is there something wrong?

Upvotes: 0

Views: 1180

Answers (1)

Josh
Josh

Reputation: 676

You need to set the Audio Category to Playback:

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

If you then want to allow mixing audio with other apps, you can add this option, just make sure to do this before setting the audio session to active.

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];

Now you can set the audio session to active:

[[AVAudioSession sharedInstance] setActive:YES error:&error];

Upvotes: 1

Related Questions