ios - 耳机插好了吗? IOS 7

标签 ios ios7 avaudioplayer avaudiosession headphones

为 iPhone 开发一个应用程序,其中包含需要通过耳机收听的音频文件。

如何检查耳机是否未插入以便告诉用户插入耳机。

我有来自另一个线程的以下代码,但不推荐使用 audioSessionGetProperty 方法。任何人都知道如何更改以下代码以使其工作或拥有自己的代码/解决方案。

谢谢。

- (BOOL)isHeadsetPluggedIn {
    UInt32 routeSize = sizeof (CFStringRef);
    CFStringRef route;


    //Maybe changing it to something like the following would work for iOS7?
    //AVAudioSession* session = [AVAudioSession sharedInstance];
    //OSStatus error = [session setCategory:kAudioSessionProperty_AudioRoute...?


    //the line below is whats giving me the warning
    OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                              &routeSize,
                                              &route);

    /* Known values of route:
     * "Headset"
     * "Headphone"
     * "Speaker"
     * "SpeakerAndMicrophone"
     * "HeadphonesAndMicrophone"
     * "HeadsetInOut"
     * "ReceiverAndMicrophone"
     * "Lineout"
     */

    if (!error && (route != NULL)) {

        NSString* routeStr = (__bridge NSString*)route;

        NSRange headphoneRange = [routeStr rangeOfString : @"Head"];

        if (headphoneRange.location != NSNotFound) return YES;

    }

    return NO;
}

最佳答案

这应该可以,但我现在无法测试,我会在晚上进行。

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

关于ios - 耳机插好了吗? IOS 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292586/

相关文章:

iOS:如何在没有 fps 下降的情况下播放音频?

ios - Swift 中的音频播放未恢复到原始音量

ios - 为什么不同swift类中的函数没有被调用?

ios - UISegmentedControl 在 UITableViewCell 中复制

iOS - 后台应用程序与本地通知

ios - 核心数据 : when is deleteObject: done?

ios - 没有在 bool 函数中获取/设置正确的返回值

bluetooth - 如何获取核心蓝牙外设的真实UUID?

iphone - 如何在 iPhone 上播放 AMR 音频文件

ios - UIActivityViewController 在 iOS7 中显示透明