检查 AVAudioPlayer 是否正在播放

Check if AVAudioPlayer is playing

我一直在尝试检查 AVAudioPlayer 当前是否正在播放,但是无论如何当我尝试这样做时它崩溃了。

我正在使用停止按钮停止音频,但是当没有音频播放时它崩溃了。

如何在我的 stopaudio 函数中检查它?

首先我定义了:

var audioPlayer = AVAudioPlayer()

我有停止按钮:

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

我试过这样检查:

if audioPlayer.playing{
    audioPlayer.stop()
}

我正在使用以下代码播放音频:

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

问题是因为 AVAudioPlayer 还没有初始化,所以我修复它的方法是初始化它然后停止它。

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

在 ViewController 中声明一个函数 class:

func tryAudio() {
        do {
            try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
        } catch {
            //handle errors
        } 

    }

在 player.stop()

之前调用 tryAudio() 初始化播放器