2011-02-07 63 views
5

我有一個綁定到onClick事件的函數。它應該播放一首歌。如果有一首歌曲正在播放,應該停止播放當前歌曲並開始播放新歌曲。唯一的問題是,據我所知,只有一個暫停方法,這意味着上一首歌曲將從暫停位置,而不是開始。有沒有辦法解決這個問題(比如.stop()方法)?在Javascript中啓動和停止音頻

這裏是我的代碼:

var currSong=""; 

function playSong(newSong){   
     alert(newSong); 
     if (newSong != ""){ 
      if(currSong != "") { 
       document.getElementById(currSong).pause(); 
      }   
      document.getElementById(newSong).play(); 
      currSong = newSong; 
     } 
} 
+0

這是HTML5音頻API? – 2011-02-07 23:19:13

+0

我猜,這是一個

回答

6

從看MDC documentation for the audio element,似乎這樣做正確的做法是通過設置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用於其他內容。