I'm trying to play a sound when my App is in the background. I use AVAudioPlayer
, and it works correctly when the app is active, but in the background AVAudioPlayer
doesn't play anything and I don't know how can I do.
I have thought that I could use UILocalNotification
, but it shows and alert in the lockscreen and I don't want it.
Thanks for your answers. I have another doubt. If I create this audiosession, and I am playing music the system will mix both at the same time?.
How can I do to decrease ipod music volume will my app sound is playing (3 seconds) and increase again when it had finished like most of the running apps in the AppStore. (In the background too)
This is my code in the AppDelegate
//Creamos la sesión de audio
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
And in my view when I want to play the sound:
-(void)avisosound{
// AudioSessionSetActive(YES);
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil){
}
else{
[audioPlayer play];
}
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
But when I play the sound, the ipod music stops.
The following tells the system to continue playing the audio even when your iPhone screen locks out:
(Most of the time you put this in your
didFinishLaunchingWithOptions
.)And to tell the system to play your audio when your app is in the background, add
UIBackgroundModes
and set it toaudio
in you plist.(Any foreground apps that need to play audio will take precedence over these settings and your app's sound playback).
To add "ducking", to lower the volume of other audio while your audio is playing, you need to implement kAudioSessionProperty_OtherMixableAudioShouldDuck. Look for that in the Audio Session programming guide.
To play a sound in the background (assuming your app has set up the proper background modes), your app has to start the sound in the foreground and not stop it. The easiest ways to do this are using the Audio Queue API or the RemoteIO Audio Unit.
You need to make couple of changes in plist file.
Then, you need to write the following code in your AppDelegate:
Now, you can easily run audio while phone screen locks or your app is in the background.
There's an article explaining what you can do in the iOS developer library. See http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html