title: Play audio file in sequence in Swift, where the second sound gets played on repeat
body: <p>For the background music in my game, I would like to play two sounds. The first sound gets played only once at the beginning (4 bar intro). Following that, the second sound (main music) gets played on an endless loop. The code below unfortunately plays the sounds simultaneously, instead of in sequence (when I looked into AVQueuePlayer, I wasn't able to figure out how to loop only the second of the two sounds):</p>
  
  <pre><code>var backgroundMusicPlayer: AVAudioPlayer!
  var backgroundMusicPlayerIntro: AVAudioPlayer!
  
  func playBackgroundMusic(filename: String, withIntro intro: String) {
      let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil)
      let resourceUrlIntro = Bundle.main.url(forResource: intro, withExtension: nil)
  
      guard let url = resourceUrl, let urlIntro = resourceUrlIntro else {
          print("Could not find files: \(intro) and/or \(filename)")
          return
      }
  
      //play the intro first before playing the main loop
      do {
          try backgroundMusicPlayerIntro = AVAudioPlayer(contentsOf: urlIntro)
          backgroundMusicPlayerIntro.numberOfLoops = 1
          backgroundMusicPlayerIntro.prepareToPlay()
          backgroundMusicPlayerIntro.play()
      } catch {
          print("Could not create audio player!")
          return
      }
  
      //main music that gets played on repeat
      do {
          try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url)
          backgroundMusicPlayer.numberOfLoops = -1
          backgroundMusicPlayer.prepareToPlay()
          backgroundMusicPlayer.play()
      } catch {
          print("Could not create audio player!")
          return
      }
  }
  </code></pre>