Playing Sound Effects while in Background Mode
I have a need to play some sporadic sound effects in the background of an iPhone app. From everything I've read and experienced with iOS 4, I can keep my app running in the background as long as I am running GPS by specifying "location" as a background mode. That actually works. But at times I want to play a sound effect...in other words, it's not "continuous" sound which I see reference to.
But the app is running, so why can't I just use AVAudioP开发者_Python百科layer to play some sound effects? Would another sound API work?
GAHHH!
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"BEEP" ofType:@"aiff"];
NSURL *fileURL = [[[NSURL alloc] initFileURLWithPath: soundFilePath] autorelease];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
player.volume = 1.0;
[player prepareToPlay];
// play
[player play];
I think it is important to clarify that your application is not running in the background. Rather, your application is 'put to sleep'. The info.plist
background process value that you specify tells the OS that it should wake your application and allow it to respond to specific types of events. From the Apple Documentation
Each of the preceding values [audio, location, voip] lets the system know that your application should be woken up at appropriate times to respond to relevant events.
In your case, your application is frozen and is only able to respond to the type of event that you specify (location, or GPS).
You don't make it clear what context this code is in, so at this point it's difficult to tell you why the audio is not playing. Also, you need to make sure that your application is running in the background for the specified purpose. If you are using the location
mechanism and not using GPS in your app, you may get rejected when you submit your application.
You may also want to refer to the Checklist for Supporting Multitasking to ensure the structure of your application implements their requirements.
[EDIT]
You have a good example of background playback while monitoring GPS position here :
http://www.informit.com/articles/article.aspx?p=1646438&seqNum=5
And it's using AudioToolbox
rather than AVAudioPlayer
I've managed to do it using the AVAudioPlayer.
did you also add the audio
value in the info.plist
for key UIBackgroundModes
?
The answer is that it won't work with AVAudioPlayer. Use the AudioServicesPlaySystemSound API instead.
精彩评论