iOS耳机那些事

判断当前耳机是否插入

#import <AVFoundation/AVFoundation.h>
- (BOOL)isHeadsetPluggedIn
{
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs])
    {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}

监听耳机插入,拔出状态

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)   name:AVAudioSessionRouteChangeNotification object:nil];


//回调
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            NSLog(@"耳机插入");
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            NSLog(@"耳机拔出,停止播放操作");
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 开发过程中录音和播放这块碰到了一些问题,麻烦的主要有三个: 检测是否有声音输入设备 当有多个声音输出设备时,指定声...
    茶饭不思阅读 1,597评论 0 4
  • 如果说一个项目出现的最重大的事故,那无疑就是开发人员使用了不可控的元素. 前言 iOS开发当中有关于视音频播放的开...
    神经骚栋阅读 10,787评论 25 73
  • 你是否看见过伟岸如山傲气十足的父亲的眼泪?我,见过。 01 去年冬天,我在病房陪护,大概5点左右,我在小床上惊醒,...
    萌果能量站阅读 446评论 6 8
  • 知行格-英雄之旅 日精进第十六日 日阅读:《活着》已读大半 日锻炼:步行若干,无强锻炼 日总结反思:今日晨起较晚,...
    林予怀_阅读 251评论 0 0
  • 《繁城》/刘素 灯火孤繁城, 春啸风声有纠纷。 昼夜为谁寂, 叹春花现又重生。 节季吹嚣城, 几多欢影几多尘。
    马帮刘素阅读 227评论 0 0