66

为 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;
}
4

8 回答 8

121

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

- (BOOL)isHeadsetPluggedIn {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}
于 2014-01-27T13:58:01.880 回答
59

只是为了扩展@Antonio 的答案。如果需要检测用户是否拔出或插入耳机。

#import <AVFoundation/AVFoundation.h>

// [AVAudioSession sharedInstance]; // @Boris edited: you may need it if there is no `AVAudioSession instance` created before. If doesn't work, uncomment this line.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)
                                             name:AVAudioSessionRouteChangeNotification
                                           object:nil];
// don't forget to `removeObserver:`

// If the user pulls out he headphone jack, stop playing.
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;

    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];

    switch (routeChangeReason) {

        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            NSLog(@"Headphone/Line plugged in");
            break;

        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            NSLog(@"Headphone/Line was pulled. Stopping player....");
            break;

        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}
于 2014-01-29T16:49:43.127 回答
12

斯威夫特 3:

检查耳机是否连接

extension AVAudioSession {

    static var isHeadphonesConnected: Bool {
        return sharedInstance().isHeadphonesConnected
    }

    var isHeadphonesConnected: Bool {
        return !currentRoute.outputs.filter { $0.isHeadphones }.isEmpty
    }

}

extension AVAudioSessionPortDescription {
    var isHeadphones: Bool {
        return portType == AVAudioSessionPortHeadphones
    }
}

然后你可以print("isHeadphones connected: \(AVAudioSession.isHeadphonesConnected)")

聆听变化

Swift 3中,语法是这样的:

func handleRouteChange(_ notification: Notification) {
    guard
    let userInfo = notification.userInfo,
    let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
    let reason = AVAudioSessionRouteChangeReason(rawValue: reasonRaw.uintValue)
    else { fatalError("Strange... could not get routeChange") }
    switch reason {
    case .oldDeviceUnavailable:
        print("oldDeviceUnavailable")
    case .newDeviceAvailable:
        print("newDeviceAvailable") 
        if AVAudioSession.isHeadphonesConnected {
             print("Just connected headphones")
        } 
    case .routeConfigurationChange:
        print("routeConfigurationChange")
    case .categoryChange:
        print("categoryChange")
    default:
        print("not handling reason")
    }
}

func listenForNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
}

注意使用:

 if AVAudioSession.isHeadphonesConnected {
    print("Just connected headphones")
 }
于 2016-09-28T14:07:39.027 回答
4

@Warif 在Swift 2.0中的代码几乎没有变化......

func audioRouteChangeListenerCallback (notif: NSNotification){
        let userInfo:[NSObject:AnyObject] = notif.userInfo!
        println("\(userInfo)")
        let routChangeReason = UInt((userInfo[AVAudioSessionRouteChangeReasonKey]?.integerValue)!)
        switch routChangeReason {
        case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
            self.println("Headphone/Line plugged in");
            break;

        case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
            //If the headphones was pulled move to speaker
            do {
                try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
            } catch _ {
            }
            self.println("Headphone/Line was pulled. Stopping player....");
            break;

        case AVAudioSessionRouteChangeReason.CategoryChange.rawValue:
            // called at start - also when other audio wants to play
            self.println("AVAudioSessionRouteChangeReasonCategoryChange");
            break;
        default:
            break;
        }
    }

:D

于 2015-09-30T16:30:27.930 回答
3

斯威夫特 3.0 版本

  • 检查耳机是否已插入或是否连接了任何具有音频输出的蓝牙设备的方法
    func bluetoothOrHeadphonesConnected() -> Bool {

        让输出 = AVAudioSession.sharedInstance().currentRoute.outputs

        在输出中输出{

            如果 output.portType == AVAudioSessionPortBluetoothA2DP ||
               output.portType == AVAudioSessionPortBluetoothHFP ||
               output.portType == AVAudioSessionPortBluetoothLE ||
               output.portType == AVAudioSessionPortHeadphones {
                返回真
            }

        }

        返回假
    }
  • 在收听任何音频时检查耳机是否已拔出很重要。
 
    私人函数 setupObservers() {

        NotificationCenter.default.addObserver(self,选择器:#selector(self.audioRouteChangeListener),名称:.AVAudioSessionRouteChange,对象:nil)

    }

    func audioRouteChangeListener(通知:通知){

        守卫让 audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] 为?其他{返回}

        切换 audioRouteChangeReason {

            案例 AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue:
                //拔掉

            默认:
                休息

        }

    }

于 2017-05-17T13:29:01.993 回答
3

在 Swift 中(从 1.2 开始):

    func headsetPluggedIn() -> Bool {
    let route = AVAudioSession.sharedInstance().currentRoute
    return (route.outputs as! [AVAudioSessionPortDescription]).filter({ $0.portType == AVAudioSessionPortHeadphones }).count > 0
}
于 2015-09-22T16:40:33.883 回答
0
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(plugout:) name:AVAudioSessionRouteChangeNotification object:nil];
-(void)plugout:(NSNotification*)notification
{
    isRemovedHeadset = YES;
}

并使用您的 isRemovedHeadset 布尔值处理您的代码

if (moviePlayer.playbackState == MPMoviePlaybackStatePaused) 
{
    if(isRemovedHeadset)
    {
        isRemovedHeadset = NO;
        [moviePlayer prepareToPlay];
        [moviePlayer play];
        return;
    }
}
于 2014-09-05T13:46:26.667 回答
0

带有 RxSwift 的 Swift 5 上的 @Sajjon 解决方案

func handleRouteChange(_ notification: Notification) {
    guard
        let userInfo = notification.userInfo,
        let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
        let reason = AVAudioSession.RouteChangeReason(rawValue: reasonRaw.uintValue)
        else { fatalError("Strange... could not get routeChange") }
    switch reason {
    case .oldDeviceUnavailable:
        print("oldDeviceUnavailable")
    case .newDeviceAvailable:
        print("newDeviceAvailable")
        if AVAudioSession.isHeadphonesConnected {
            print("Just connected headphones")
        }
    case .routeConfigurationChange:
        print("routeConfigurationChange")
    case .categoryChange:
        print("categoryChange")
    default:
        print("not handling reason")
    }
}

func listenForNotifications() {
    NotificationCenter.default.rx
        .notification(AVAudioSession.routeChangeNotification)
        .subscribe(onNext: { (n) in
            self.handleRouteChange(n)
        })
        .disposed(by: disposeBag)
}
于 2019-07-26T13:56:02.633 回答