在我的应用程序中,我必须录制音频并播放此音频并在您的耳朵附近播放此音频时添加接近度,因此为此我必须在播放按钮单击时执行此代码:
- (IBAction)btnPlayPauseTapped:(id)sender {
UIDevice *device = [UIDevice currentDevice];
[device setProximityMonitoringEnabled: YES];
if (device.proximityMonitoringEnabled == YES) {
[[NSNotificationCenter defaultCenter] removeObserver:APP_DELEGATE name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:APP_DELEGATE selector:@selector(proximityChanged:) name:@"UIDeviceProximityStateDidChangeNotification" object:device];
//other code
}
启用接近时通知调用此方法:
- (void) proximityChanged:(NSNotification *)notification {
NSLog(@"proximity changed called");
UIDevice *device = [notification object];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if(device.proximityState == 1){
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
[audioSession setActive:YES error:nil];
}
else{
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
[audioSession setActive:YES error:nil];
}
}
当播放器停止播放或暂停时,我添加以下内容:
UIDevice *device = [UIDevice currentDevice];
[device setProximityMonitoringEnabled: NO];
但是当我再次开始播放音频并将设备放在耳朵附近时,它调用了通知方法(proximityChanged),当时接近状态也得到 1,音频会话类别也设置为 playandrecord 但它没有在耳机中播放此音频。它在主扬声器中播放音频。
请帮助我。
先感谢您。