【发布时间】:2010-03-25 23:57:23
【问题描述】:
是否可以检测到用户将外接耳机插入 iPhone 的 3.5 毫米连接器或 30 针连接器?我只想将音频输出到外部音频设备,如果没有连接,则保持静音。
【问题讨论】:
标签: iphone objective-c core-audio
是否可以检测到用户将外接耳机插入 iPhone 的 3.5 毫米连接器或 30 针连接器?我只想将音频输出到外部音频设备,如果没有连接,则保持静音。
【问题讨论】:
标签: iphone objective-c core-audio
答案与this question 的答案非常相似,但您需要改为获取kAudioSessionProperty_AudioRoute 属性。
【讨论】:
调用该方法判断蓝牙耳机是否连接。
首先导入这个框架#import <AVFoundation/AVFoundation.h>
- (BOOL) isBluetoothHeadsetConnected
{
AVAudioSession *session = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *routeDescription = [session currentRoute];
NSLog(@"Current Routes : %@", routeDescription);
if (routeDescription)
{
NSArray *outputs = [routeDescription outputs];
if (outputs && [outputs count] > 0)
{
AVAudioSessionPortDescription *portDescription = [outputs objectAtIndex:0];
NSString *portType = [portDescription portType];
NSLog(@"dataSourceName : %@", portType);
if (portType && [portType isEqualToString:@"BluetoothA2DPOutput"])
{
return YES;
}
}
}
return NO;
}
【讨论】:
Apple 文档中有一篇很好的文章: https://developer.apple.com/documentation/avfoundation/avaudiosession/responding_to_audio_session_route_changes
只有你必须验证 portType == AVAudioSessionPortBluetoothA2DP
func setupNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(handleRouteChange),
name: .AVAudioSessionRouteChange,
object: nil)
}
@objc func handleRouteChange(notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
let session = AVAudioSession.sharedInstance()
for output in session.currentRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
headsetConnected = true
break
}
case .oldDeviceUnavailable:
if let previousRoute =
userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
for output in previousRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
headsetConnected = false
break
}
}
default: ()
}
}
func isBluetoothHeadsetConnected() -> Bool {
var result = false
let session = AVAudioSession.sharedInstance()
for output in session.currentRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
result = true
}
return result
}
【讨论】: