AVPlayer停止播放时如何禁用接近度

how to disable proximity when AVPlayer stop playing

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

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

请帮帮我。

提前致谢。

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

  - (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];

    }