Search code examples
swiftavaudioplayer

Check if AVAudioPlayer is playing


I've been trying to check if the AVAudioPlayer is currently playing, but when I try to do it in anyway it crashes.

I'm using stop button to stop the audio but when there is no audio playing it crashes.

How is it possible to check it in my stopaudio function ?

First I defined :

var audioPlayer = AVAudioPlayer()

I have stop button :

func stopaudio(sender: AnyObject){
    audioPlayer.stop()
}

I tried to check like this :

if audioPlayer.playing{
    audioPlayer.stop()
}

I am using the following code to play the audio :

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

Solution

  • The problem was because the AVAudioPlayer hasn't been initialized yet, so what i did to fix it is to initialize it and then stop it.

    var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("013", ofType: "m4a")!)!
    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
    audioPlayer.stop()