MPMoviePlayerController stops iPod playback and doesn't restart
I've got an iPhone app with a short intro video. If a user launches the app while their iPod is playing music, the music will stop while the video plays (whether or not the video has sound), and the audio stays permanently stopped after video playback. Apple seems to indicate that you can solve this with AudioSession tricks: https://web.archive.org/web/20100819124854/http://developer.apple.com:80/iPhone/library/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/WorkingWithOpenALiPodMusicandMovies/WorkingWithOpenALiPodMusicandMovies.html
But their suggestions here just don't seem to work; it seems like MPMoviePlayerController overrides the audio session configuration for its own purposes. Ideally I'd mix the movie audio over the iPod audio or maybe use ducking, 开发者_Go百科but even restarting the music might be a passable fix.
I've found a great solution for that. In the .h file, you must create a BOOL called "wasPlaying". Before playing your video, you ask the iPod if it was playing.
if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying)
{
NSLog(@"Music was playing, lets put YES to the bool");
wasPlaying = YES;
}
Then, after you tell the movie player to play, you call the following:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedPlaying) name:MPMoviePlayerPlaybackDidFinishNotification object: moviePlayer];
And after that, in the method finishedPlaying:
if (wasPlaying ==YES)
{
NSLog(@"Music was playing, lets play music again");
[[MPMusicPlayerController iPodMusicPlayer] play];
}
For me it worked fine!
I think you can do this by initializing the audio session similar to this:
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryAmbient
error:&audioSessionError] == YES)
Then when you want to use the audio session you can set the iPod audio to duck the video track:
AudioSessionInitialize (NULL, NULL, NULL, NULL);
OSStatus propertySetError = 0;
UInt32 allowMixing = true;
propertySetError |= AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(allowMixing), &allowMixing);
AudioSessionSetActive(YES);
You can only have a single music-providing app at any time and multiple sources of (brief) sounds. If a background app is playing music, your app can overlay brief sounds. If you want to play music, the background app has to be stopped.
So I don't think that what you're trying to achieve is possible using MPMoviePlayerController (or any of the high-level audio frameworks). You might be able to overlay an audio track of a movie, if it's sufficiently short but MPMoviePlayerController is probably not good for this.
精彩评论