javascript - HTML5 音频 - 当另一个声音开始时停止当前播放

标签 javascript html audio

我使用此方法在单击图像时播放音频文件:

http://jsfiddle.net/v97Kq/3/

function imageSwitch(_imgID, _imgStart, _imgStop, _soundFileMp3, _soundFileOgg) {
    this.imgID = _imgID;
    this.imgStart = _imgStart;
    this.imgStop = _imgStop;
    this.song = new Audio();
    if (this.song.canPlayType("audio/mpeg"))
        this.song.src = _soundFileMp3;
    else 
        this.song.src = _soundFileOgg;
    this.song.loop = true;

    this.pos = 0;
    this.e;

    this.change = function () {
        if (this.pos == 0) {
            this.pos = 1;
            document.getElementById(this.imgID).src = this.imgStop;
            this.song.play();
        } else {
            this.pos = 0;
            document.getElementById(this.imgID).src = this.imgStart;
            this.song.pause();
        }
    }
}

效果很好! - 但是当单击另一个链接并且另一个声音开始时,如何让它停止播放当前播放的声音?

最佳答案

我发现这个解决方案可以解决我的上述问题,效果非常好。 我最终找到了here :

<script>
var currentPlayer;
function EvalSound(soundobj) {

 var thissound=document.getElementById(soundobj);
 if(currentPlayer  && currentPlayer != thissound) {
  currentPlayer.pause(); 
 }
 if (thissound.paused)
        thissound.play();
    else
    thissound.pause();
    thissound.currentTime = 0;
     currentPlayer = thissound;
}
</script>

关于javascript - HTML5 音频 - 当另一个声音开始时停止当前播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679101/

相关文章:

javascript - 我怎样才能通过javascript知道html的显示部分是什么

javascript - 使用网络音频 API 播放多个声音时如何消除噪音?

android - 消除音量信封重新触发点击 - Android 上的 Jsyn

javascript - 使用 jQuery 之后,href 链接不起作用

javascript - jquery 的 click() 中 this.variable = NaN

html - 需要使用 CSS 选择小于其 'option' 宽度的 'select' 元素

java - 如何使用 libgdx 播放音乐

javascript - 从mysql结果数组中获取值

javascript - 如何将上传的图像插入到 <IMG> 标签/占位符中?

c# - 如何使用 WinForms 中的 Web 浏览器控件访问 HTML 文档的 <HEAD> 元素?