How to resume audio after the phone call ends.
Here is my code but it is not working don’t know why
@interface MainViewController : UIViewController <InfoDelegate, AVAudioPlayerDelegate>
In m file
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer;
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer;
{
[self.audioPlayer play];
}
Any ideas what is it i m doing wrong or missing from code.
Please help.
Depending on how your audio was stopped (did you call
[self.audioPlayer stop]?) you may have to call[self.audioPlayer prepareToPlay]before callingplayagain.I believe what you ought to do is the following:
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer; { [self.audioPlayer pause]; } -(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer; { [self.audioPlayer play]; }In my experience, if you call
stopyou then must callprepareToPlaybefore you can callplayagain.EDIT:
Alternatively, you may need to handle interruptions via the AudioSession directly.
Your app should initialize the AudioSession, something like this:
Then, implement
AudioInterruptionListeneroutside your@implementation/@endblock, something like this:#define kAudioEndInterruption @"AudioEndInterruptionNotification" #define kAudioBeginInterruption @"AudioBeginInterruptionNotification" void AudioInterruptionListener ( void *inClientData, UInt32 inInterruptionState ) { NSString *notificationName = nil; switch (inInterruptionState) { case kAudioSessionEndInterruption: notificationName = kAudioEndInterruption; break; case kAudioSessionBeginInterruption: notificationName = kAudioBeginInterruption; break; default: break; } if (notificationName) { NSNotification *notice = [NSNotification notificationWithName:notificationName object:nil]; [[NSNotificationCenter defaultCenter] postNotification:notice]; } }Back in your Objective-C, you’ll need to listen for the notifications that this code may post, something like this:
// Listen for audio interruption begin/end [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginAudioInterruption:) name:kAudioBeginInterruption object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endAudioInterruption:) name:kAudioEndInterruption object:nil];And:
-(void)beginAudioInterruption:(id)context { [self.audioPlayer pause]; } -(void)endAudioInterruption:(id)context { [self.audioPlayer play]; }Give that a whirl. 🙂