//这里我用的是AVAudioPlayer
- (void)viewDidLoad {
[super viewDidLoad];
//-->在通知中心注册一个事件中断的通知:
//处理中断事件的通知
//-->实现接收到中断通知时的方法
//处理中断事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:nil];
NSBundle *bundle=[NSBundle mainBundle];
NSString *urlString=[bundle pathForResource:@"陈一发儿 - 童话镇" ofType:@"mp3"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:urlString];
AVAudioPlayer *player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
player.delegate=self;
player.numberOfLoops=99;
self.player=player;
}
-(void)handleInterreption:(NSNotification *)sender
{
int type = [sender.userInfo[AVAudioSessionInterruptionOptionKey] intValue];
switch (type) {
case AVAudioSessionInterruptionTypeBegan: // 被打断
NSLog(@"播放");
//这里要写一个dowhile循环,因为如果直接写一句播放语句的话,有时候如果打电话立马挂了,多试几次,可能会不播放,所以要写循环,直到状态为播放为止;,至于为什么,我也没有搞清楚,可能是bug,也可能是我没找对方法吧
do {
NSLog(@"循环");
[self.player prepareToPlay];
[self.player play];
} while (!self.player.playing);
break;
case AVAudioSessionInterruptionTypeEnded: // 中断结束
NSLog(@"暂停");
[self.player pause];
break;
default:
NSLog(@"其他");
break;
}
}
2改进方案,之前一直觉得写个循环总觉得不是多么对,终于现在找到了一个问题点
在后台时,我们暂停播放不要用pause方法,用stop方法就可以了,亲测半天,果然问题出在这里。以下为改进代码:
-(void)handleInterreption:(NSNotification *)sender
{
int type = [sender.userInfo[AVAudioSessionInterruptionOptionKey] intValue];
switch (type) {
case AVAudioSessionInterruptionTypeBegan: // 被打断
{
NSLog(@"播放");
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
// do {
// NSLog(@"循环");
// [self.player prepareToPlay];
// [self.player play];
// } while (!self.player.playing);
//[self.player prepareToPlay];
[self.player play];
}
break;
case AVAudioSessionInterruptionTypeEnded: // 中断结束
{
NSLog(@"暂停");
[self.player stop];
AVAudioSession *audioSession=[AVAudioSession sharedInstance];
[audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}
break;
default:
NSLog(@"其他");
break;
}
}
以上1和2注释的东西可要可不要。