¿Los auriculares están enchufados? iOS7

Desarrollar una aplicación para un iPhone con files de audio que también se deben escuchar a través de auriculares.

¿Cómo verifico si los auriculares no están enchufados, por lo que puedo decirle al usuario que conecte los auriculares.

Tengo el siguiente código de otro hilo pero el método audioSessionGetProperty está en desuso. Alguien sabe cómo modificar el siguiente código para que esto funcione O tener su propio código / solución.

Gracias.

- (BOOL)isHeadsetPluggedIn { UInt32 routeSize = sizeof (CFStringRef); CFStringRef route; //Maybe changing it to something like the following would work for iOS7? //AVAudioSession* session = [AVAudioSession shanetworkingInstance]; //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; } 

Esto debería funcionar, pero no puedo probarlo ahora, lo haré por la noche.

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

Solo para extender la respuesta de @ Antonio. Si necesita detectar si el usuario ha sacado o enchufado los auriculares.

 #import <AVFoundation/AVFoundation.h> 

 // [AVAudioSession shanetworkingInstance]; // @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; } } 

El código de @ Warif en Swift 2.0 con pequeños cambios …

 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.shanetworkingInstance().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; } } 

:RE

Swift 3:

Para verificar si los auriculares están conectados

 extension AVAudioSession { static var isHeadphonesConnected: Bool { return shanetworkingInstance().isHeadphonesConnected } var isHeadphonesConnected: Bool { return !currentRoute.outputs.filter { $0.isHeadphones }.isEmpty } } extension AVAudioSessionPortDescription { var isHeadphones: Bool { return portType == AVAudioSessionPortHeadphones } } 

Luego puede print("isHeadphones connected: \(AVAudioSession.isHeadphonesConnected)")

Escuchando cambios

En Swift 3 la syntax es la siguiente:

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

Aviso de uso de:

  if AVAudioSession.isHeadphonesConnected { print("Just connected headphones") } 

En Swift (a partir de 1.2):

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

Versión Swift 3.0

  • Método para verificar si los auriculares están conectados o cualquier dispositivo Bluetooth con salida de audio conectada
     func bluetoothOrHeadphonesConnected () -> Bool {

         dejar salidas = AVAudioSession.shanetworkingInstance (). currentRoute.outputs

         para salida en salidas {

             if output.portType == AVAudioSessionPortBluetoothA2DP ||
                output.portType == AVAudioSessionPortBluetoothHFP ||
                output.portType == AVAudioSessionPortBluetoothLE ||
                output.portType == AVAudioSessionPortHeadphones {
                 devuelve verdadero
             }

         }

         falso retorno 
     }
  • Es importante verificar si los auriculares están enchufados mientras escucha cualquier audio.
 
     function privada setupObservers () {

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

     }

     func audioRouteChangeListener (notificación: notificación) {

         guard deje que audioRouteChangeReason = notification.userInfo! [AVAudioSessionRouteChangeReasonKey] como?  Int else {return}

         cambiar audioRouteChangeReason {

             caso AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue:
                 // enchufado

             defecto:
                 descanso

         }

     }

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

y maneje su código usando este isRemovedHeadset boolean en su

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