美文网首页
iOS系统音量与耳机插入拔出监听

iOS系统音量与耳机插入拔出监听

作者: Vson2016 | 来源:发表于2018-08-20 16:48 被阅读52次

    一、系统音量的监听

        // 创建单例对象并且使其设置为活跃状态.
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        // 需要开启该功能以便监听系统音量
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        // 添加监听系统音量变化
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
    

    回调方法:

    - (void)onVolumeChanged:(NSNotification *)notification {
        if ([[notification.userInfo objectForKey:@"AVSystemController_AudioCategoryNotificationParameter"] isEqualToString:@"Audio/Video"]) {
            if ([[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"] isEqualToString:@"ExplicitVolumeChange"]) {
                CGFloat volume = [[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
                NSLog(@"volume: %@", @(volume));
            }
        }
    }
    

    二、耳机的插入与拔出

        // 创建单例对象并且使其设置为活跃状态.
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        // 添加监听耳机插入与拔出
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    

    回调方法:

    - (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
        NSDictionary *interuptionDict = notification.userInfo;
        NSInteger routeChangeReason   = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
        
        switch (routeChangeReason) {
            case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
                NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
                //插入耳机
                break;
            case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
                NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
                //拔出耳机
                break;
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS系统音量与耳机插入拔出监听

          本文链接:https://www.haomeiwen.com/subject/dxmliftx.html