如何在电话结束后恢复音频。
这是我的代码,但它不起作用,不知道为什么
@interface MainViewController : UIViewController <InfoDelegate, AVAudioPlayerDelegate>
在m档案中
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer;
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer;
{
[self.audioPlayer play];
}
任何想法是什么,我在代码中做错了或丢失了。
请帮忙。
答案 0 :(得分:2)
根据您的音频停止方式(您是否致电[self.audioPlayer stop]
?),您可能需要再次致电[self.audioPlayer prepareToPlay]
,然后再次致电play
。
我相信你应该做的是以下几点:
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer; { [self.audioPlayer pause]; } -(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer; { [self.audioPlayer play]; }
根据我的经验,如果您致电stop
,则必须先致电prepareToPlay
,然后才能再次致电play
。
修改强>
或者,您可能需要直接通过AudioSession处理中断。
您的应用应初始化AudioSession,如下所示:
AudioSessionInitialize(NULL, NULL, AudioInterruptionListener, NULL);
然后,在AudioInterruptionListener
/ @implementation
块之外实施@end
,如下所示:
#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]; } }
回到Objective-C,您需要收听此代码可能发布的通知,如下所示:
// 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];
和
-(void)beginAudioInterruption:(id)context { [self.audioPlayer pause]; } -(void)endAudioInterruption:(id)context { [self.audioPlayer play]; }
给那个旋转。 : - )