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

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

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

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

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容