title: Swift Audio from Video: Default to speaker
body: <p>I am trying to play a video on the iPhone and it would be ideal if the audio from the video came out on the iPhone loud speaker.</p>
  
  <p>However, i get this error on my console:</p>
  
  <blockquote>
    <p>audioSession error: The operation couldn’t be completed. (OSStatus error -50.)</p>
  </blockquote>
  
  <p>Here is my code ::</p>
  
  <pre><code>    let player = AVPlayer(url: video_url)
  
      let audioSession = AVAudioSession.sharedInstance()
  
      do {
          try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
      } catch let error as NSError {
          print("audioSession error: \(error.localizedDescription)")
      }
  
      // get the lenght of the video
      self.video_duration = getMediaDuration(url: video_url) + 0.25
  
      // notification for when video is over.
      NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
  
      // the video controller...
      let controller = AVPlayerViewController()
      controller.view.frame = self.view.frame
      controller.player = player
      controller.showsPlaybackControls = false
      controller.view.tag = 99
      self.video_ctrl = controller
  
      // add controller as subview
      self.view.addSubview(controller.view)
      controller.player?.play()
  </code></pre>
  
  <p>I googled the error, and haven't seen any results.
  Any help is appreciated.</p>
  
  <p>Later on in the same app, I play an audio file using the same lines above for <strong>AVAudioSession</strong> and that works just fine. After that, if I replay the video, the sound will come out on the speaker, like I want it. But why does it NOT happen the first time?</p>