Cesare
Cesare

Reputation: 9419

How do you make the music keep going even when going to a new ViewController in Swift?

I would like to play a mp3 file in a UIViewController. Though, when the user leaves the view controller the music stops. How do I keep it playing?

var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("musicFileHere", ofType: "mp3")!)!
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()    

Upvotes: 0

Views: 139

Answers (1)

Cesare
Cesare

Reputation: 9419

Add audioPlayer.play so your whole code looks like this:

var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("musicFileHere", ofType: "mp3")!)!
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()   
audioPlayer.play

Upvotes: 1

Related Questions