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

2018-08-20  本文已影响52人  Vson2016

一、系统音量的监听

    // 创建单例对象并且使其设置为活跃状态.
    [[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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读