HTML5音频多重播放

4

我正在编写一个JavaScript游戏,希望使用同一个声音多次。我可以通过将同一个声音加载到数组中来实现此目的。但是我希望只加载一次声音,然后将其“复制”到数组中,这样就可以多次播放它。这是我现在使用的方法:

this.list = [
        "LaserShot", //http://www.freesound.org/samplesViewSingle.php?id=39459
        "Ding", //http://www.freesound.org/samplesViewSingle.php?id=5212
        "Rocket" //http://www.freesound.org/samplesViewSingle.php?id=47252 -> http://creativecommons.org/licenses/sampling+/1.0/
    ];

...

for (i in this.list) {
        this.sounds[this.list[i]] = new Array();

        for (var j = 0; j < this.channels; j++) {
            this.sounds[this.list[i]][j] = new Audio("./sounds/"+ this.list[i] + type);
        }
    }

我只想做这个:

for (i in this.list) {
        this.sounds[this.list[i]] = new Array();

var tempAudio = new Audio("./sounds/"+ this.list[i] + type);

        for (var j = 0; j < this.channels; j++) {
            this.sounds[this.list[i]][j] = realCopyOfTempAudio;
        }
    }

非常感谢您。
1个回答

0

我的经验:

最好创建多个具有相同源的音频HTML标签。我是JavaScript的粉丝,但这次使用HTML表单中的音频标签更好。

我复制了音频标签并满足了我的需求。如果您想在一秒钟内播放相同的声音多次,则添加更多克隆。

另外,您可以修复自动播放的错误(而不是EXE_JUST_ONE_TIME),您可以使用覆盖点击事件,现在不重要):

    <audio controls id="LaserShot" >
     <source src="LaserShot.mp3" type="audio/mpeg">
     <source src="LaserShot.ogg" type="audio/ogg">
    </audio>
     <audio controls id="LaserShot_CLONE" >
     <source src="LaserShot.mp3" type="audio/mpeg">
     <source src="LaserShot.ogg" type="audio/ogg">
    </audio>

<script>

  var EXE_JUST_ONE_TIME = false;

  document.addEventListener("click" , function(e) {

    if (EXE_JUST_ONE_TIME == false){

      EXE_JUST_ONE_TIME = true;

      document.getElementById("LaserShot").play();
      document.getElementById("LaserShot").pause();

      document.getElementById("LaserShot_CLONE").play();
      document.getElementById("LaserShot_CLONE").pause();

      // Buffering in progress 
      // now you can play programmability from code
      // One click or touch can prepare max 6 audios 

    }
 }


Last part (need to be handled) this handler works only for one clone:


    var play_shoot = function(){

     if (document.getElementById('LaserShot').duration > 0 &&
       !document.getElementById('LaserShot').paused) {

      document.getElementById('LaserShot_CLONE').play();

     } else {

      document.getElementById('LaserShot').play();

     }

    }

感谢您回复我五年前的问题。我会在有时间的时候尝试,并且如果它有效,我会将您的问题标记为已解决。 - Tomáš Nesrovnal
即使在今天,在没有自动播放功能的移动浏览器上,这个答案仍然是实际的! - Nikola Lukic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接