可能重复:
如何确定外部耳机是否连接到 iPhone?
我正在开发一个音频播放器应用程序,并且在其中一种模式(播放模式)下,我想检测耳机的状态,如果插入了插孔,它应该播放,否则不应该播放。
编辑下面是我的代码片段,也有关于我想要做什么的解释。我从 SO 上的其他线程中找到了大部分代码,但仍然无法让它按我想要的方式运行。
- (void)isHeadsetPluggedIn {
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route);
NSString* routeStr = (NSString*)route;
NSRange headsetRange = [routeStr rangeOfString : @"Headset"];
NSRange receiverRange = [routeStr rangeOfString : @"Receiver"];
if(headsetRange.location != NSNotFound) {
// Don't change the route if the headset is plugged in.
NSLog(@"headphone is plugged in ");
//here is the place i want to play music
/* AVAudioPlayer *mySound;
mySound =[[AVAudioPlayer alloc]initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"apple_SIMToolkitPositiveACK" withExtension:@"mp3" ]error:nil];
[mySound play];
//here is the place where i must receive the info about plug-in(headset)
*/
}
else if (receiverRange.location != NSNotFound) {
// Change to play on the speaker
NSLog(@"play on the speaker");
}
else {
NSLog(@"Unknown audio route.");
}
}