[音频]检测音频口设备

本方法主要用于检测音频口设备是否插入。
以对其做了iOS 7判断优化。

分别加入
[objc]
AudioToolbox.framework
AVFoundation.framework
[/objc]
引入
[objc]
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVAudioSession.h>
[/objc]
以及自定义宏
[objc]
#define iOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
[/objc]
代码如下:
[objc]
– (BOOL)hasHeadset {

#if TARGET_IPHONE_SIMULATOR //[宏]判断是否为模拟器
#warning *** Simulator mode: audio session code works only on a device
//由于模拟器没有音频口可以测试,所以默认返回NO;
return NO;
#else

if (iOS7) {
//由于iOS 7 会提示AudioSessionGetProperty被弃用,所以我们使用AVAudioSession来代替
//备注:该方法必须在 iOS 6 之后版本使用。
NSArray *headsetAr =[[[AVAudioSession sharedInstance] currentRoute] outputs];
AVAudioSessionPortDescription *port =[headsetAr objectAtIndex:0];

NSLog(@"端口设备: %@ %@",[port portName],[port portType]);

NSRange headphoneRange = [[port portType] rangeOfString : @"Headphone"];
NSRange headsetRange = [[port portType] rangeOfString : @"Headset"];
if (headphoneRange.location != NSNotFound) {
return YES;
} else if(headsetRange.location != NSNotFound) {
return YES;
}
return NO;

}else{

CFStringRef route;
UInt32 propertySize = sizeof(CFStringRef);

AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);
//获取到音频会话属性值。
if((route == NULL) || (CFStringGetLength(route) == 0)){
//音频线路为静音模式
} else {
NSString* routeStr = (__bridge NSString*)route;
NSLog(@"音频线路: %@", routeStr);

/* 已知的线路有如下:
* 由于在 iOS Developer Library 找不到准确资料,
* 所以下面资料来源于 StackOverflow 仅供参考
* "Headset"
* "Headphone"
* "Speaker"
* "SpeakerAndMicrophone"
* "HeadphonesAndMicrophone"
* "HeadsetInOut"
* "ReceiverAndMicrophone"
* "Lineout"
*/

NSRange headphoneRange = [routeStr rangeOfString : @"Headphone"];
NSRange headsetRange = [routeStr rangeOfString : @"Headset"];
if (headphoneRange.location != NSNotFound) {
return YES;
} else if(headsetRange.location != NSNotFound) {
return YES;
}
}
return NO;
}

#endif
}
[/objc]

93 thoughts on “[音频]检测音频口设备

  1. 國產 av

    I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. All the best

  2. hi88

    You really make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand. It seems too complicated and extremely broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

  3. hi88

    Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your website? My blog site is in the exact same niche as yours and my visitors would definitely benefit from some of the information you provide here. Please let me know if this okay with you. Cheers!

Bqoxpx进行回复 取消回复

电子邮件地址不会被公开。