Routing iPhone Audio Sound

后端 未结 3 592
醉话见心
醉话见心 2021-02-04 20:08

I have an app which does listen and play sound at the same time. By default, the sound output goes through the earphone. So I use the following code to route it through the spea

3条回答
  •  忘了有多久
    2021-02-04 20:41

    To do this you have to add property listener when you setup audio session:

    AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioSessionPropertyListener, nil);
    

    Where

    void audioSessionPropertyListener(void* inClientData, AudioSessionPropertyID inID,
                                              UInt32 inDataSize, const void* inData) {
              UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    
              if (!isHeadsetPluggedIn()) 
                AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
            }
    
    BOOL isHeadsetPluggedIn() {
      UInt32 routeSize = sizeof (CFStringRef);
      CFStringRef route;
    
      OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                                &routeSize,
                                                &route
                                                );
    
    
    
         if (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound)) {
            NSLog(@"HeadsetPluggedIn");
            return YES;
          }
          NSLog(@"Headset_NOT_PluggedIn");
          return NO;
        }
    

    So when headphones are plugged in or out you get a notification and change audio output direction.

提交回复
热议问题