ios音乐播放中断处理

阅读: 评论:0

ios音乐播放中断处理

ios音乐播放中断处理

//这里我用的是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注释的东西可要可不要。

本文发布于:2024-02-02 12:40:17,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170684881843863.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:音乐播放   ios
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23