title: Headphones unplugged during playback cause bug on iPhone app
body: <p>I am creating an application based on the <strong>Speak Here example app</strong>. I want the audio to play through the headphones if they are plugged in or otherwise default to the speakers.</p>
  
  <p>I've used the bottom bit of code to make this happen and it works fine unless the headphones are unplugged during playback. At that point the playback ends, which is okay. The problem is when I hit play again the playback comes out all weird and the stop button stops working. It also starts playback from where it left off rather then resetting from the beginning as it normally does when you hit the stop button. </p>
  
  <p>Likewise if the headphones are plugged in before the app opens this also results in strange behaviour.</p>
  
  <p>Maybe I need to grab the 'headphones unplugged' event and get it to 'press the stop button'? Because the way it is doing it now is not correct. </p>
  
  <p>To put my question in a simple form: <strong>How do you properly setup core audio on the iPhone for playback through the speakers and headphones.</strong> </p>
  
  <p><strong>Any pieces of code that could solve this problem would be of great help</strong>. Thanks!</p>
  
  <pre><code> OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);
  
  if (error) printf("ERROR INITIALIZING AUDIO SESSION! %d\n", error);
  else 
  {
      UInt32 category = kAudioSessionCategory_PlayAndRecord;  
      // UInt32 category = kAudioSessionCategory_MediaPlayback;   
  
      error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &amp;category);
      if (error) printf("couldn't set audio category!");
  
  
      // It is bugs when I unplug the headphones! 
      UInt32 doChangeDefaultRoute = 1;        
      AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &amp;doChangeDefaultRoute);
  
  
  
  
      error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, propListener, self);
      if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
      UInt32 inputAvailable = 0;
      UInt32 size = sizeof(inputAvailable);
  
      // we do not want to allow recording if input is not available
      error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &amp;size, &amp;inputAvailable);
      if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", error);
      btn_record.enabled = (inputAvailable) ? YES : NO;
  
      // we also need to listen to see if input availability changes
      error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, propListener, self);
      if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
  
      error = AudioSessionSetActive(true); 
      if (error) printf("AudioSessionSetActive (true) failed");
  </code></pre>