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

时间:2015-10-16 09:16:16

标签: ios avplayer proximitysensor

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

- (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 :(得分: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];

    }