title: AVAudioSession setCategory not working
body: <p>I have a video capturing app and I want to be able to play background music while recording audio+video.</p>
  
  <p>I can accomplish this if I set the <code>AVAudioSession</code> category to <code>PlayAndRecord</code> in <code>didFinishLaunchingWithOptions</code>. However, this causes a glitch in the audio whenever the view with the camera enters or exits the foreground, and its apparently impossible to get rid of: <a href="https://forums.developer.apple.com/message/74778#74778" rel="nofollow noreferrer">https://forums.developer.apple.com/message/74778#74778</a></p>
  
  <p>I can live with the glitch if it just happens when I start/stop recording video, but that means I need to change the <code>AVAudioSession</code> category from <code>Ambient</code> to <code>PlayAndRecord</code> when a button is pressed, and this also seems to not be possible.</p>
  
  <p>How do I change the <code>AVAudioSession</code> category?</p>
  
  <p>I tried this:</p>
  
  <pre><code>[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                   withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                         error:nil];
  </code></pre>
  
  <p>But the background music stops when the recording starts.</p>
  
  <p>Following this post: <a href="https://stackoverflow.com/questions/21869802/avcapturesession-and-background-audio-ios-7">AVCaptureSession and background audio iOS 7</a></p>
  
  <p>I tried deactivating the session then setting the category:</p>
  
  <pre><code>AVAudioSession *session = [AVAudioSession sharedInstance];
  [session setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&amp;error];
  [session setCategory:AVAudioSessionCategoryPlayAndRecord
           withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker
                 error:nil];
  [session setActive:YES error:&amp;error];
  </code></pre>
  
  <p>I also tried listening for the <code>AVAudioSessionRouteChangeNotification</code> and setting the category in that handler after deactivating the session. But the background music always turns off when the app starts recording.</p>
  
  <p>Why can't I change the <code>AVAudioSession</code> category?</p>