如何真正停止快速播放音频

jam*_*n34 1 avaudioplayer ios swift

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

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

我想我需要某种方法来“清除”来自 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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

esq*_*qew 5

AVAudioPlayer.stop文档(强调我的):

stop 方法不会将 currentTime 属性的值重置为 0。换句话说,如果您stop在播放期间调用play,然后调用 ,则播放会从停止的点恢复

相反,请考虑利用该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()
    }
}
Run Code Online (Sandbox Code Playgroud)