[英]How to really stop audio from playing in 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()
}
}
從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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.