首页 文章

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

提问于
浏览
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,音频会话类别也会设置为播放和记录,但它不会在耳机中播放此音频 . 它在主扬声器中播放音频 .

请帮帮我 .

先感谢您 .

1 回答

  • 0

    我在2天之后解决了我的问题,当玩家停止播放器因为我禁用接近度是正确的但是我在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];
    
        }
    

相关问题