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

时间:2014-11-18 14:07:03

标签: iphone swift core-audio ios8.1

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

- (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来生成频率,但是在视图控制器中使用swift所以需要一种方法来实现一个监听器来检测耳机插件事件并返回到用户到上一个视图,我不知道我是否可以使用我的函数isHeadsetPluggedin()与事件监听器或我应该创建一个新的。 在我的MenuViewController中,我控制是否使用以下功能插入耳机:

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

3 个答案:

答案 0 :(得分:6)

article对我有用。还有GitHub repo解决方案。如果您不想阅读,请参阅以下代码:

将它放在您的INIT方法中:

    self.session = AVAudioSession.sharedInstance()
    let currentRoute = self.session.currentRoute
    if currentRoute.outputs.count != 0 {
        for description in currentRoute.outputs {
            if description.portType == AVAudioSessionPortHeadphones {
                print("headphone plugged in")
            } else {
                print("headphone pulled out")
            }
        }
    } else {
        print("requires connection to device")
    }

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: #selector(YOUR_VIEW_CONTROLLER_OR_VIEW.audioRouteChangeListener(_:)),
        name: AVAudioSessionRouteChangeNotification,
        object: nil)

把它放在你班上的任何地方:

 dynamic private func audioRouteChangeListener(notification:NSNotification) {
    let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt

    switch audioRouteChangeReason {
    case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
        print("headphone plugged in")
    case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
        print("headphone pulled out")
    default:
        break
    }
}

小心!

答案 1 :(得分:3)

您可以通过观察AVAudioSessionRouteChangeNotification通知来跟踪路线更改。

//Observe for route changing notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];

   -(void)handleRouteChange:(NSNotification *)notif
    {
       NSDictionary *dict = notif.userInfo;
       AVAudioSessionRouteDescription *routeDesc = dict[AVAudioSessionRouteChangePreviousRouteKey];
       AVAudioSessionPortDescription *prevPort = [routeDesc.outputs objectAtIndex:0];
       if ([prevPort.portType isEqualToString:AVAudioSessionPortHeadphones]) {
            //Head phone removed
          }
     }

答案 2 :(得分:0)

在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: ()
            }

        }