title: Swift: How to stop Background music when changing views
body: <p>I'm trying to get the background music to stop playing when changing to another view. </p>
  
  <p>I have a global variable to play the music</p>
  
  <pre><code>import Foundation
  import AVFoundation
  
  class MusicHelper {
      static let sharedHelper = MusicHelper()
      var audioPlayer: AVAudioPlayer?
  
      func playBackgroundMusic() {
          let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "The Walking Dead", ofType: "mp3")!)
          do {
              audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
              audioPlayer!.numberOfLoops = -1
              audioPlayer!.prepareToPlay()
              audioPlayer!.play()
          } catch {
              print("Cannot play the file")
          }
      }
  }
  </code></pre>
  
  <p>And then I load the music into the view here</p>
  
  <pre><code>import UIKit
  import SwiftGifOrigin
  import AVFoundation
  
  class ViewController: UIViewController {
      var audioPlayer: AVAudioPlayer?
  
      @IBOutlet weak var introGif: UIImageView!
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // Gif intro
          self.introGif.image = UIImage.gifWithName("WalkingDeadIntro")
  
          _ = try! Data(contentsOf: Bundle.main.url(forResource: "WalkingDeadIntro", withExtension: "gif")!)
          //self.bottomImageView.image = UIImage.gif(data: imageData)
  
          // Load background Music
          MusicHelper.sharedHelper.playBackgroundMusic()
      }
  </code></pre>