I have an app which plays music in the background during a game, which supports multitasking. When I press the home button, an action is called on applicationWillResignActive. This pulls up the pause screen and pauses the game. BUT, when I implemented music in the game, things went wrong. I used the AVAudioPlayer to play my background music. When applicationWillResignActive is called, in the same action that brings up the pause screen, the music is told to pause. But when you go back in the app via multitasking, the pause screen is still showing as it should, but the music is also still playing. I have tried in numerous places to stop the music but it refuses to stop. Even after switching views, the music still plays. It is completely unrespo开发者_如何学Pythonnsive.
This is extremely frustrating. Please help!
I have spent hours today with precisely the same problem.
I finally have a workaround.
The #stop method releases the hardware, but doesn't forget the current playback position.
So you can call #play again and playback resumes as desired.
My previous code was:
[player pause];
...
if ([player isPaused]) { [player play]; }
This of course didn't work, and playback happily resumed after the app came back into the foreground, as you have experienced.
Now I have something like this:
self.playbackSuspended = YES;
[player stop];
...
if (self.playbackSuspended) { [player play]; }
A hack, but it works. The only drawback is that #prepareToPlay is implicitly called to regain ownership of the playback hardware, re-buffer, etc. so there might be a delay in playback - I have not noticed one so far.
Also note that depending on your implementation, handling interruptions such as phone calls may be broken after the above hack. Phone call interruptions behave correctly, so by hacking like above, any shared code will likely be in a confused state for interruption handing.
精彩评论