How to stop audio player in swift

2.4k Views Asked by At

So in my app the user plays an instrumental when they hit the play button but when they stop it should stop the music. In my code when i add the code for the stop button nothing plays when i hit the play button but when i delete the code the play button works but the stop button doesn't. I don't see why its doing that in my code.

Here is code:

@IBAction func playInstrumentalPressed(sender: AnyObject) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let saveFileName = nameSavedFile as String
    if (saveFileName != "") {
        let beatLocation = documentsPath + "/" + saveFileName + ".wav"
        let fileURL = NSURL(fileURLWithPath: beatLocation)

        var error:NSError?

        player = AVAudioPlayer(contentsOfURL: fileURL, error: &error)

        if player.prepareToPlay() && player.play() {
            println("yes")
        } else {
            println("no")
        }

    } else {
        println("Not Available") //add alertview here
    }
}

@IBAction func stopInstrumentalButton(sender: UIButton) {
    if (player.playing) {
        player.stop()
    } else {
        println("Nothing is playing")
    }
      }
1

There are 1 best solutions below

0
On BEST ANSWER

I wonder if you might have your iBAction outlets hooked up incorrectly... Maybe double check your xib/storyboard to see what methods the buttons are hooked up to