gpt4 book ai didi

iphone - Swift 中的耳机插件/输出检测

转载 作者:可可西里 更新时间:2023-10-31 23:56:36 25 4
gpt4 key购买 nike

我正在开发适用于 iOS 8.1 的 iPhone 应用程序,该应用程序与核心音频一起使用以生成频率并调整强度。在我生成我需要控制的频率的 View Controller 中,如果耳机在某个时刻被拔出,我已经在控制是否连接耳机,然后使用以下功能进入我的频率发生器 View :

- (BOOL)isHeadsetPluggedIn {
AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
for (AVAudioSessionPortDescription* desc in [route outputs]) {
if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
return YES;
}
return NO;
}

此函数在 C 中,因为我使用 core-audio 来生成频率,但在 View Controller 中我使用 swift,因此需要一种方法来实现监听器以检测耳机拔出事件并返回到用户回到以前的 View ,我不知道我是否可以将我的函数 isHeadsetPluggedin() 与事件监听器一起使用,或者我应该创建一个新的。在我的 MenuViewController 中,我使用以下函数控制是否插入耳机:

func isHeadsetPluggedIn() -> Bool {
return freqController.isHeadsetPluggedIn();
}

最佳答案

在 Swift 4 中

    func activateHeadPhonesStatus(){
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListener(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
}

@objc func audioRouteChangeListener(_ notification:Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
let session = AVAudioSession.sharedInstance()
for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
headphonesConnected = true
print("headphone plugged in")
break
}
case .oldDeviceUnavailable:
if let previousRoute =
userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
headphonesConnected = false
print("headphone pulled out")
break
}
}
default: ()
}

}

关于iphone - Swift 中的耳机插件/输出检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com