Swift中的耳机插件/输出检测 [英] Headphones plugin/out detection in Swift

查看:178
本文介绍了Swift中的耳机插件/输出检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

im working on an iphone app for iOS 8.1 that works with core audio to generate frequencies and adjust intensities. In the view controller that i generate the frequencies i need to control if the headphones are plugged out in some moment, i'm already controlling if headphones are connected before proceed to my frequencies generator view with the following function:

- (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中,我控制是否使用以下功能插入耳机:

this function is in C because im working with core-audio to generate the frequencies, but in the view controllers im working with swift so a need a way to implement a listener to detect the headphones plug-out event and return to the user to the previous view, i don't know if i can use my function isHeadsetPluggedin() with an event listener or i should make a new one. In my MenuViewController i control if the headphones are plugged in using the following function:

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


推荐答案

您可以跟踪路线变化通过观察 AVAudioSessionRouteChangeNotification 通知。

You can track the route changes by observing AVAudioSessionRouteChangeNotification notification.

//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
          }
     }

这篇关于Swift中的耳机插件/输出检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆