【问题标题】:Starting and Stopping Audio in Javascript在 Javascript 中启动和停止音频
【发布时间】:2011-06-23 02:33:02
【问题描述】:

我有一个绑定到 onClick 事件的函数。它应该播放一首歌。如果有一首歌曲已经在播放,它应该停止当前歌曲并开始播放新歌曲。唯一的问题是,据我所知,只有一个 pause 方法,这意味着上一首歌将从暂停位置恢复,而不是从开始。有没有办法解决这个问题(比如 .stop() 方法)?

这是我的代码:

var currSong="";

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

【问题讨论】:

标签: javascript audio


【解决方案1】:

通过查看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 用于其他用途。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多