2015-10-16 89 views
1

在我的应用程序,我有录制音频和播放音频,并添加接近时,播放音频您的耳朵附近所以为了这个,我不得不这样做代码时播放按钮点击:如何禁用接近时AVPlayer停止播放

- (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,音频会话类别也设置为播放和记录,但是它没有在耳边扬声器中播放这个音频。它在主扬声器中播放音频。

请在这帮助我。

先谢谢您。

回答

0

我解决了我的问题2天后,当玩家停止播放器,因为我禁用接近是正确的,但我改变了audiosession类别在接近变化的方法。

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

    }