简体   繁体   English

Javascript音频分层事件监听器HTML5多次迭代失败

[英]Javascript audio layering eventListener HTML5 fails on multiple iterations

I am working on putting together an audio function for use on a simple script to play notes like those on a piano. 我正在研究一种音频功能,以便在简单的脚本上使用以弹奏钢琴上的音符。 My solution to the audio tags inability to handle a new request until it has played through was to create a new audio element for every subsequent click, then set a listener to remove that element once it had played its sound. 对于无法处理新请求直到播放完毕的音频标签,我的解决方案是为每次后续单击创建一个新的音频元素,然后设置一个侦听器以在播放声音后删除该元素。 It works great except that it seems as though my event listener is overwritten, so only the last iteration of the sound is followed, leaving numerous audio elements intact and inactive. 它的工作原理很不错,除了似乎我的事件侦听器被覆盖了,因此只跟踪声音的最后一次迭代,而使许多音频元素保持完整且处于非活动状态。

Code: 码:

var x = 0;
function playSound(){
  x = x + 1;
  var na = document.createElement('audio');
  na.setAttribute('id','cycle'+x);
  document.body.appendChild(na);
  var ta = document.getElementById('cycle'+x);
  var ns = document.createElement('source');
  ns.setAttribute('src','notify.wav');
  ta.appendChild(ns);
  document.getElementById('cycle'+x).addEventListener('ended', function(){
  document.body.removeChild(document.getElementById('cycle'+x));
    try{document.getElementById('cycle'+x).remove();}
    catch(err){}});
  ta.play();
}

and to preload the sound into the page: 并将声音预加载到页面中:

<audio id="preloader" preload="auto"><source src="notify.wav"></source></audio>

I am wanting to have individual event listeners for each generated audio element, so that when the file has played, the element is removed. 我希望每个生成的音频元素都有单独的事件侦听器,以便在播放文件时删除该元素。

Your problem stems from a referencing issue - by the means used in your sample code you cannot fetch the desired element in the current scope within the listener. 您的问题源于引用问题-通过示例代码中使用的方式,您无法在侦听器中的当前作用域中获取所需的元素。

Safari's console tells me this: Safari的控制台告诉我:

[Error] NotFoundError: DOM Exception 8: An attempt was made to reference a Node in a context where it does not exist.
(anonymous function) (_display, line 33)

Obviously all event listeners are firing correctly. 显然,所有事件侦听器都可以正确触发。

Of course you could go on a massive hunt to find the true reason behind this, but since you are looking for a solution to your problem, this should do: 当然,您可以进行大规模的搜索以找出背后的真正原因,但是由于您正在寻找解决问题的方法,因此应该这样做:

Remove these lines: 删除这些行:

document.body.removeChild(document.getElementById('cycle'+x));
try{document.getElementById('cycle'+x).remove();}
catch(err){}});

And replace them with: 并替换为:

this.remove();

The event listener callback will always provide the related element as this . 事件监听器回调将始终提供与this相关的元素。 And that is your safest route to a valid reference. 这是您获得有效参考的最安全途径。

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

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