1

在我的应用程序中,我必须录制音频并播放此音频并在您的耳朵附近播放此音频时添加接近度,因此为此我必须在播放按钮单击时执行此代码:

- (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 但它没有在耳机中播放此音频。它在主扬声器中播放音频。

请帮助我。

先感谢您。

4

1 回答 1

0

我在 2 天后解决了我的问题,因为当我禁用接近时播放器停止播放器是正确的,但我在接近更改方法中更改了音频会话类别。

  - (void) proximityChanged:(NSNotification *)notification {
    UIDevice *device = [notification object];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL success;
     success = [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    if(device.proximityState == 1){
        NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
        [audioSession setActive:YES error:nil];
    }
    else{
         NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        [audioSession setActive:YES error:nil];

    }
于 2015-10-19T10:35:56.583 回答