項(xiàng)目中有音頻播放,當(dāng)手機(jī)有來電和耳機(jī)拔插等行為時(shí),需要做一些操作
來電監(jiān)聽,創(chuàng)建CTCallCenter
@property (nonatomic, strong) CTCallCenter *callCenter ;/*!*電話監(jiān)聽*/
初始化callCenter
if (!self.callCenter) {
self.callCenter = [[CTCallCenter alloc] init];
}
在callCenter的一些事件處理callEventHandler,是一個(gè)block回調(diào),我用__weak來調(diào)用屬性,避免block中內(nèi)存泄漏
__weak typeof(self) weakSelf = self;
self.callCenter.callEventHandler = ^(CTCall* call) {
if ([call.callState isEqualToString:CTCallStateDisconnected]){
NSLog(@"掛斷了電話咯");
}else if ([call.callState isEqualToString:CTCallStateConnected]){
NSLog(@"電話通了");
}else if([call.callState isEqualToString:CTCallStateIncoming]){//在這里可以做一些操作,比如:記錄來電話前播放器狀態(tài)
NSLog(@"來電話了");
//來電話了,由于是音頻項(xiàng)目,監(jiān)聽來電事件
if (weakSelf.player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {//AVPlayer系統(tǒng)方法,檢測(cè)播放器狀態(tài),是播放狀態(tài)還是暫停狀態(tài)
}else if((weakSelf.player.timeControlStatus == AVPlayerTimeControlStatusPaused)){
//記錄播放器狀態(tài),用中間變量記錄狀態(tài)可以保證全局使用
}
}else if ([call.callState isEqualToString:CTCallStateDialing]){
NSLog(@"正在播出電話call is dialing");
}else{
NSLog(@"什么都沒做");
}
監(jiān)聽耳機(jī)拔插
監(jiān)聽耳機(jī)是一個(gè)系統(tǒng)的單例方法,通過發(fā)送通知來做操作
[[AVAudioSession sharedInstance] setActive:YES error:nil];//創(chuàng)建單例對(duì)象并且使其設(shè)置為活躍狀態(tài).
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];//設(shè)置通知
實(shí)現(xiàn)通知方法
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
NSLog(@"耳機(jī)插入");
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
//耳機(jī)拔出
dispatch_async(dispatch_get_main_queue(), ^{
//做操作,用主線程調(diào)用,如果不用主線程會(huì)報(bào)黃,提示,從一個(gè)線程跳到另一個(gè)線程容易產(chǎn)生崩潰,所以這里要用主線程去做操作
});
break;
}