ios音乐播放中断处理
2017-02-21 19:28
459 查看
//这里我用的是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注释的东西可要可不要。
相关文章推荐
- IOS处理音乐播放中断实例
- ios处理播放音频时的中断
- iOS播放音乐文件时的操作和打断处理
- iOS播放音乐文件时的操作和打断处理
- iOS AVAudioPlayer和AVAudioPlayerDelegate-音频播放处理中断
- ios-UI高级 相册的相关处理和音乐播放AVFoundation框架的内容总结
- ios播放声音中断后台音乐的问题
- ios播放声音中断后台音乐的问题
- IOS音乐后台播放的实现
- ios后台播放音乐
- iOS后台播放背景音乐文件
- IOS的后台模式播放音乐( BackGroundMode)
- iOS后台播放音乐
- IOS 播放音乐实例 .
- IOS-使用AVAudioPlayer播放音乐文件
- iOS后台播放背景音乐文件
- ios播放音乐
- 音乐播放例子 ios 可显示左右声道的音频
- IOS锁屏状态播放音乐时显示专辑信息和图片
- IOS 播放音乐实例