今下午項目中使用到了 揚聲器和聽筒的設置,我項目中是這樣的,有一個聊天設置,聊天設置有一個使用揚聲器 播放聲音的設置。
這個設置是,當你打開那個開關的話,你在聊天中都可以根據你的使用來任意的播放聲音,今下午在網上查了一下,好多都是那幾行代碼,基本上都是復制同一個人的,搞的我拷貝他們的代碼,竟然用不了,需要修改,我就進行了修改,運用到了我的項目中來,我的代碼是這樣的,我的代碼中,有一個設置是判斷那個開關是否打開,如果打開的狀態我就是擴音器播放,沒打開就是話筒播放,因為我開關是一個button按鈕,所以我的判斷是判斷他 是0 或者 是1了。。
1 #pragma mark ----聲音的播放 2 -(void)Playthevoice:(UIButton *)btn 3 { 4 self.voiceData=[NSData dataWithContentsOfFile:_wavfilePath]; 5 if ([self.delegate respondsToSelector:@selector(returnselfcell:)]) { 6 [self.delegate returnselfcell:self]; 7 } 8 9 NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults]; 10 NSString *isMessage=[userdefault objectForKey:@"isSpeaker_Set"]; 11 if ([isMessage isEqualToString:@"1"]) { 12 13 //初始化播放器的時候如下設置 14 UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; 15 AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, 16 sizeof(sessionCategory), 17 &sessionCategory); 18 19 UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; 20 AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, 21 sizeof (audioRouteOverride), 22 &audioRouteOverride); 23 24 AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 25 //默認情況下揚聲器播放 26 [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; 27 [audioSession setActive:YES error:nil]; 28 29 [self SensorNotification:YES]; 30 31 }else if ([isMessage isEqualToString:@"0"]) 32 { 33 34 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; 35 36 } 37 }
在下面我首先我先注冊了一個監聽的通知,這里我用了網上的方法,設置了如果你靠在耳朵上聽的話,屏幕就會變暗,和撥打電話一樣的處理,如果我的設置那里的布爾值為YES,則會來調用這個通知。這個通知就會來調用我的這個擴音器播放的這個方法。這個方法是我上面的 Playthevoice 方法里面的調用
[self SensorNotification:YES];
1 #pragma mark - 監聽聽筒or揚聲器 2 - (void) SensorNotification:(BOOL)state 3 { 4 [[UIDevice currentDevice] setProximityMonitoringEnabled:state]; //建議在播放之前設置yes,播放結束設置NO,這個功能是開啟紅外感應 5 6 if(state)//添加監聽 7 [[NSNotificationCenter defaultCenter] addObserver:self 8 selector:@selector(sensorVoiceStateChange:) name:@"UIDeviceProximityStateDidChangeNotification" 9 object:nil]; 10 else//移除監聽 11 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil]; 12 } 13 14 //處理監聽觸發事件 15 -(void)sensorVoiceStateChange:(NSNotificationCenter *)notification; 16 { 17 //如果此時手機靠近面部放在耳朵旁,那么聲音將通過聽筒輸出,並將屏幕變暗(就為省一點電啊,可以讓你勾搭妹紙了。哈哈) 18 if ([[UIDevice currentDevice] proximityState] == YES) 19 { 20 NSLog(@"Device is close to user"); 21 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; 22 } 23 else 24 { 25 NSLog(@"Device is not close to user"); 26 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 27 } 28 }
基本上就是這些了,邏輯就是 你按鈕那里觸發了,擴音器播放,然后你的那個代理那里就會來執行這個擴音器播放的這個方法。然后根據你的這個判斷來進行設置擴音器或者聽筒了。。。