在Javascript中启动和停止音频
问题描述:
我有一个绑定到onClick事件的函数。它应该播放一首歌。如果有一首歌曲正在播放,应该停止播放当前歌曲并开始播放新歌曲。唯一的问题是,据我所知,只有一个暂停方法,这意味着上一首歌曲将从暂停位置,而不是开始。有没有办法解决这个问题(比如.stop()方法)?在Javascript中启动和停止音频
这里是我的代码:
var currSong="";
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "") {
document.getElementById(currSong).pause();
}
document.getElementById(newSong).play();
currSong = newSong;
}
}
答
从看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用于其他内容。
这是HTML5音频API? – 2011-02-07 23:19:13
我猜,这是一个