简体   繁体   English

Javascript HTML 音频仅调用一次时重复播放功能

[英]Javascript HTML Audio repeats play function when only called once

I have the below function that is part of a bigger function but I eliminated all of the parts that aren't part of the problem.我有以下功能,它是更大功能的一部分,但我消除了所有不属于问题的部分。

The function creates an audio tag and puts it in the body.该函数创建一个音频标签并将其放入正文中。 I'm using this method instead of the audio API because I'm using createMediaElementSource which requires the HTML element.我使用此方法而不是音频 API,因为我使用的是需要 HTML 元素的createMediaElementSource

After the ended event is finished and you click the replay button, the play function is called twice, despite only being triggered once.ended事件完成并单击replay按钮后,尽管只触发了一次,但play函数会被调用两次。

I tried putting the code in a snippet, but I couldn't duplicate the problem so I had to put it in a fiddle instead.我试着把代码放在一个片段中,但我无法复制这个问题,所以我不得不把它放在一个小提琴中。 - https://jsfiddle.net/6n2f34eh/ - https://jsfiddle.net/6n2f34eh/

On the full function, there is user interaction that activates the playing.在完整功能上,有激活播放的用户交互。

<button type="button" class="btn-replay">REPLAY</button>

var func = function() {
  that = this;
  that.sound;

  this.init = function() {
    document.querySelector(".btn-replay").addEventListener("click", that.play);
    tag = document.createElement("audio");
    tag.className = "player";
    document.body.appendChild(tag);
    that.sound = document.querySelector(".player");
    that.sound.src = 'https://www2.cs.uic.edu/~i101/SoundFiles/CantinaBand3.wav';
    that.sound.addEventListener("canplaythrough", this.play);
    that.sound.addEventListener("ended", this.ended);
  }

  this.ended = function() {
    console.log("ended")
  }

  this.play = function() {
    console.log("play")
    that.sound.play();
  }

  this.init();

}

test = new func();

You've got two event listeners that result in the play function being called - "click" on the button and "canplaythrough" on the sound.您有两个导致调用播放函数的事件侦听器 - 按钮上的“单击”和声音上的“canplaythrough”。 Right after you click the button, the audio loads from the link so both events are fired.单击按钮后,音频将从链接加载,因此两个事件都会被触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM