iOS下微信語音播放之切換聽筒和揚聲器的方法

setProximityMonitoringEnabled
不知道是應該叫紅外感應還是應該叫什么,就是打電話的時候會自動黑屏的那個API,原來沒注意過。

 UIDevice *_curDevice = [UIDevice currentDevice];
[_curDevice setProximityMonitoringEnabled:YES];
NSNotificationCenter *_defaultCenter = [NSNotificationCenter defaultCenter];
[_defaultCenter addObserverForName:UIDeviceProximityStateDidChangeNotification
                          object:nil
                           queue:[NSOperationQueue mainQueue]
                      usingBlock:^(NSNotification *note) {
                        if (_curDevice.proximityState == YES) {
                          NSLog(@"怕是黑屏了吧");
                        }
                        else {
                          NSLog(@"屏幕應該亮了");
                        }
                      }];

 [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; //建議在播放之前設置yes,播放結束設置NO,這個功能是開啟紅外感應
 //添加監聽
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification"  object:nil]; 
//處理監聽觸發事件 
-(void)sensorStateChange:(NSNotificationCenter *)notification{
//如果此時手機靠近面部放在耳朵旁,那么聲音將通過聽筒輸出,并將屏幕變暗(省電啊)
if ([[UIDevice currentDevice] proximityState] == YES) {
NSLog(@"Device is close to user");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
}else{
NSLog(@"Device is not close to user");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
}
//初始化播放器的時候如下設置
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory),&sessionCategory);
UInt32 audioRouteOverride = 
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//默認情況下揚聲器播放
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容