iPhone 音量键拍照 自拍杆拍照功能

2018-07-24  本文已影响327人  little_ma

本文采用通知方式控制音量键的执行:

优点:
可以监听到音量键的每次调节,即使音量调整到最大或者最小依然能够收到通知。手机静音条件下也能收到此通知。

- (void)addCameraSystemVolumeObserver:(void(^)(void))block
{
    [self hiddenVolumeView];
    NSError *error;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:YES error:&error];
    // 记住当前的音量,防止拍照影响APP的音量
    CGFloat currentVol = audioSession.outputVolume;
    
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:@"AVSystemController_SystemVolumeDidChangeNotification"
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification * _Nonnull note)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *changeReason = [note.userInfo valueForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
            // 判断监听的消息是否为我们需要的调整音量的操作
            if ([changeReason isEqualToString:@"ExplicitVolumeChange"]) {
                
                float volumeValue = [[note.userInfo valueForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
                // 判断是否为恢复操作
                if (volumeValue != currentVol) {
                    if (block) {
                        block();
                    }
                    
                    [weakSelf returnToOriginVolume:currentVol];
                }
            }
        });
    }];
}


针对AVSystemController_SystemVolumeDidChangeNotification通知的方式所遇到的问题及解决方案:
1)、该消息除了监听音量键之外,应用切换前后台也会发送该消息,所以,还需要判断消息的userInfo的字段AVSystemController_AudioVolumeChangeReasonNotificationParameter,确定发送消息的理由,value值为ExplicitVolumeChange就是我们所需要的。

NSNotification === {
    "AVSystemController_AudioCategoryNotificationParameter" = "Audio/Video";
    "AVSystemController_AudioVolumeChangeReasonNotificationParameter" = RouteChange;
    "AVSystemController_AudioVolumeNotificationParameter" = "0.3125";
    "AVSystemController_UserVolumeAboveEUVolumeLimitNotificationParameter" = 0;
}
NSNotification === {
    "AVSystemController_AudioCategoryNotificationParameter" = "Audio/Video";
    "AVSystemController_AudioVolumeChangeReasonNotificationParameter" = ExplicitVolumeChange;
    "AVSystemController_AudioVolumeNotificationParameter" = "0.375";
    "AVSystemController_UserVolumeAboveEUVolumeLimitNotificationParameter" = 0;
}

2)、如何解决音量键拍照会改变系统的音量问题:
开始监听时,获取当前的音量,并记下;在执行音量拍照后恢复原来的音量。当然恢复原来的音量,又会收到对应的调节音量的通知,注意排除掉本次的回调。

上一篇 下一篇

猜你喜欢

热点阅读