如何在 swift 中真正停止播放音频

How to really stop audio from playing in swift

在我的应用程序中,我有一个计时器。当用户启动计时器时,它会播放一段铃声。此音频剪辑响起(共鸣)几秒钟。用户可以随时重新启动计时器,当他们重新启动时,应该会再次播放铃声。

发生的情况是,如果在轻按重启时铃声音频仍在播放,则由于重叠而不会再次播放铃声。我认为将代码添加到 .stop() 它然后再添加 .play() 就可以了,但它没有用。相反,重启按钮看起来就像一个 pause/play 按钮,当您点击按钮时,您可以听到铃声共鸣。

我想我需要一些方法来 "clear out" 从 AVAudioPlayer() 播放任何音频,但我不知道该怎么做(搜索互联网也没有帮助)。

这是我的代码:

@IBAction func RestartTimerBtn(_ sender: Any) {

        timer.invalidate() // kills the past timer so it can be restarted

        // stop the bell audio so it can be played again (usecase: when restarting right after starting bell)
        if audioPlayer_Bell.isPlaying == true{
            audioPlayer_Bell.stop()
            audioPlayer_Bell.play()
        }else {
            audioPlayer_Bell.play()
        }
    }

来自 AVAudioPlayer.stop docs(强调我的):

The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off.

相反,考虑利用 currentTime 属性 在再次 play 播放之前向后跳到声音的开头:

@IBAction func RestartTimerBtn(_ sender: Any) {

    timer.invalidate() // kills the past timer so it can be restarted

    if audioPlayer_Bell.isPlaying == true{
        audioPlayer_Bell.stop()
        audioPlayer_Bell.currentTime = 0
        audioPlayer_Bell.play()
    }else {
        audioPlayer_Bell.play()
    }
}