mercredi 20 mai 2015

Xcode (Swift) AVFoundation prevent background music playing twice when returning to first screen

I am fairly new to Xcode and am still learning my way around. At the moment I have a home screen which plays background music using AVFoundation. If you click play the music stops (which is what I want).

If you move to the instructions screen the music continues (which I want), however when you click to return to home screen the background music continues (which I want), but a new track starts over the top.

in my mind What I ideally need is an if statement which prevents the music from restarting when I return to the home screen (if it is already playing). I have scoured the internet but I can't find any suggestions that will work.

This is the what I am currently working with,

class firstPageViewController: UIViewController {



override func viewDidLoad() {
    super.viewDidLoad()

    backgroundMusic = self.setupAudioPlayerWithFile("background", type:"mp3")
    backgroundMusic.volume = 0.3
    backgroundMusic.numberOfLoops = -1
    backgroundMusic.play()


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


var backgroundMusic = AVAudioPlayer()

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
    //1
    var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
    var url = NSURL.fileURLWithPath(path!)

    //2
    var error: NSError?

    //3
    var audioPlayer:AVAudioPlayer?
    audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

    //4
    return audioPlayer!
}



@IBAction func startGame(sender: UIButton) {

    backgroundMusic.stop()

}

@IBAction func instructionsButton(sender: UIButton) {

}

Any help would be really appreciated!

thanks

Aucun commentaire:

Enregistrer un commentaire