简体   繁体   English

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

[英]How to really stop audio from playing in swift

In my app I have a timer. 在我的应用程序中,我有一个计时器。 When the user starts the timer it plays a bell audio clip. 当用户启动计时器时,它将播放铃声音频剪辑。 This audio clip rings (resonates) for a few seconds. 此音频片段会响起(共鸣)几秒钟。 The user can restart the timer at any time and when they do, it's supposed to play the bell audio clip again. 用户可以随时重新启动计时器,而在这样做时,应该重新播放铃声音频剪辑。

What's happening is that if the bell audio is still playing when the restart is tapped it does not play the bell audio again due to this overlap. 发生的情况是,如果在单击重新启动时铃声仍在播放,则由于此重叠,它不会再次播放铃声。 I thought adding code to .stop() it and then .play() it again would do the trick, but it did not work. 我以为将代码添加到.stop()然后再将.play()可以解决问题,但是没有用。 Instead it seems like the restart button is acting like a pause/play button, you can hear the bell audio clip resonating when you tap the button. 取而代之的是,似乎重新启动按钮就像是暂停/播放按钮,当您点击该按钮时,您会听到铃声音频片段产生共鸣。

I think I need some way to "clear out" any playing audio from the AVAudioPlayer() but I can't figure out how to do that (and searching the internet hasn't helped). 我想我需要某种方法来“清除”来自AVAudioPlayer()的任何播放音频,但是我不知道该怎么做(搜索互联网没有帮助)。

Here is my code: 这是我的代码:

@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()
        }
    }

From the AVAudioPlayer.stop docs (emphasis mine): AVAudioPlayer.stop文档 (重点是我):

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 . stop方法不会将currentTime属性的值重置为0。换句话说,如果您在播放期间调用stop ,然后调用play ,则播放将从其停止处恢复

Instead, consider leveraging the currentTime property to skip backwards to the beginning of your sound before play ing it again: 相反,请考虑利用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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM