Program Tip

헤드폰이 연결되어 있습니까?

programtip 2020. 11. 22. 20:26
반응형

헤드폰이 연결되어 있습니까? IOS 7


헤드폰으로도들을 필요가있는 오디오 파일이있는 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;
}

@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;
    }
}

스위프트 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)")

변화에 귀 기울이기

에서는 신속한 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")
 }

Swift 2.0 에서 @Warif의 코드는 거의 변경되지 않았습니다.

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

:디


Swift에서 (1.2부터) :

    func headsetPluggedIn() -> Bool {
    let route = AVAudioSession.sharedInstance().currentRoute
    return (route.outputs as! [AVAudioSessionPortDescription]).filter({ $0.portType == AVAudioSessionPortHeadphones }).count > 0
}

Swift 3.0 버전

  • 헤드폰이 연결되어 있는지 또는 오디오 출력이 연결된 Bluetooth 장치가 연결되어 있는지 확인하는 방법
    func bluetoothOrHeadphonesConnected ()-> Bool {

        let outputs = AVAudioSession.sharedInstance (). currentRoute.outputs

        출력용 {

            if output.portType == AVAudioSessionPortBluetoothA2DP ||
               output.portType == AVAudioSessionPortBluetoothHFP ||
               output.portType == AVAudioSessionPortBluetoothLE ||
               output.portType == AVAudioSessionPortHeadphones {
                참을 반환
            }

        }

        거짓 반환 
    }
  • 오디오를 듣는 동안 헤드폰이 연결되어 있는지 확인하는 것이 중요합니다.
 
    private func setupObservers () {

        NotificationCenter.default.addObserver(self, selector: #selector(self.audioRouteChangeListener), name: .AVAudioSessionRouteChange, object: nil)

    }

    func audioRouteChangeListener(notification: Notification) {

        guard let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as? Int else { return }

        switch audioRouteChangeReason {

            case AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue:
                //plugged out

            default:
                break

        }

    }


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(plugout:) name:AVAudioSessionRouteChangeNotification object:nil];
-(void)plugout:(NSNotification*)notification
{
    isRemovedHeadset = YES;
}

and handle your code using this isRemovedHeadset boolean in your

if (moviePlayer.playbackState == MPMoviePlaybackStatePaused) 
{
    if(isRemovedHeadset)
    {
        isRemovedHeadset = NO;
        [moviePlayer prepareToPlay];
        [moviePlayer play];
        return;
    }
}

@Sajjon solution on Swift 5 with RxSwift

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

참고URL : https://stackoverflow.com/questions/21292586/are-headphones-plugged-in-ios7

반응형