[英]Starting and Stopping Audio in Javascript
我有一個函數綁定到onClick事件。 應該播放一首歌。 如果已經在播放一首歌曲,則應該停止當前歌曲並開始播放新歌曲。 唯一的問題是,據我所知,只有一種暫停方法,這意味着上一首歌曲將從暫停位置而不是開始位置恢復。 有什么辦法解決這個問題(如.stop()方法)?
這是我的代碼:
var currSong="";
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
document.getElementById(newSong).play();
currSong = newSong;
}
}
通過查看audio
元素的MDC文檔 ,似乎正確的方法是設置currentTime
屬性:
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
var newSongEl = document.getElementById(newSong);
newSongEl.currentTime = 0;
newSongEl.play();
currSong = newSong;
}
}
另外,最好將相關元素存儲在currSong
,而不是將其存儲在ID中,除非您將ID用於其他用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.