Play background music in app?

user4984255 picture user4984255 · Jul 15, 2015 · Viewed 9.8k times · Source

I want the user to be able to open the app and have music start playing. I want the user to be able to go any view controller and return back to the initial one without the music stopping. I want it to loop indefinitely.

I have tried to put in the viewDidLoad method of the initial view controller for it to start playing. What happens is, the user leaves the initial view controller and when they come back, the music starts playing again, overlapping the original copy.

To remedy this, I put an if statement checking if the sound is already to playing to not launch another copy and the viewDidLoad method completely ignores the if statement and plays it again anyways. I also tried using viewDid/WillAppear. I have tried putting the sound in the app delegate in the applicationDidLaunchWithOptions method and I got complete silence.

Answer

Astri picture Astri · Jan 9, 2016

Using a singleton works as well:

Swift 3 or later

import AVFoundation

class MusicHelper {
    static let sharedHelper = MusicHelper()
    var audioPlayer: AVAudioPlayer?
    
    func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coolsong", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }
}

Swift 2.2.1 or earlier

import AVFoundation

class MusicHelper {
    static let sharedHelper = MusicHelper()
    var audioPlayer: AVAudioPlayer?
    
    func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coolsong", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL:aSound)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }
}

Then you can use it from any class (as per Swift 2.1)

MusicHelper.sharedHelper.playBackgroundMusic()