title: In iOS created application to force audio output via speaker, but doesn't work when application is in background
body: <p>I want to implement, when i plugged in headset/headphone in iPhone and play any music, music should play from speaker instead of headphone.
  So using this below code that working fine when my application is in foreground. But when my application goes in background that time this code is not working. </p>
  
  <ul>
  <li>I want to implement  this functionality in 3 case
  
  <ol>
  <li>When application is in foreground.</li>
  <li>When application is in background.</li>
  <li>When application remove from backgound.</li>
  </ol></li>
  </ul>
  
  <p>Please give me solution for that.</p>
  
  <p>I have used this below code,</p>
  
  <pre><code> + (void) initAudioSessionRouting{
  
      // Called once to route all audio through speakers, even if something's plugged into the headphone jack
      static BOOL audioSessionSetup = NO;
      if (audioSessionSetup == NO) {
  
          // set category to accept properties assigned below
          NSError *sessionError = nil;
          [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error: &amp;sessionError];
  
          // Doubly force audio to come out of speaker
          UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
          AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &amp;audioRouteOverride);
  
          // fix issue with audio interrupting video recording - allow audio to mix on top of other media
          UInt32 doSetProperty = 1;
          AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &amp;doSetProperty);
  
          // set active
          [[AVAudioSession sharedInstance] setDelegate:self];
          [[AVAudioSession sharedInstance] setActive: YES error: nil];
  
          // add listener for audio input changes
          AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, onAudioRouteChange, nil );
          AudioSessionAddPropertyListener (kAudioSessionProperty_AudioInputAvailable, onAudioRouteChange, nil );
  
      }
  
      // Force audio to come out of speaker
      [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
      // set flag
      audioSessionSetup = YES;}
  </code></pre>
  
  <p>Thanks in advance</p>