iOS系統(tǒng)音量與耳機(jī)插入拔出監(jiān)聽

一、系統(tǒng)音量的監(jiān)聽

    // 創(chuàng)建單例對象并且使其設(shè)置為活躍狀態(tài).
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    // 需要開啟該功能以便監(jiān)聽系統(tǒng)音量
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    // 添加監(jiān)聽系統(tǒng)音量變化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

回調(diào)方法:

- (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));
        }
    }
}

二、耳機(jī)的插入與拔出

    // 創(chuàng)建單例對象并且使其設(shè)置為活躍狀態(tài).
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    // 添加監(jiān)聽耳機(jī)插入與拔出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];

回調(diào)方法:

- (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason   = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            //插入耳機(jī)
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            //拔出耳機(jī)
            break;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容