faster way for calling audio element to play in html5

元气小坏坏 提交于 2019-12-13 01:19:41

问题


I'm trying to use audio elemnt in HTML5 mobile game. I have some problems with sound effects,so I clone the audio elemnt many times in the start of the game like that :

for (var i=0; i < 10; i++)
        {
            var container = document.getElementById("audioDiv");
            var clone = document.getElementById('multiaudio0').cloneNode(true);
            clone.setAttribute('id',"multiaudio" + i);
            container.appendChild (clone);
        };

Then when I need to use it "in collision" ,I call it as NEXT :

document.getElementById('audioDiv').getElementsByTagName("audio")[score%10].play();

The problem that it is very slow and slow down the animation on canvas while calling the element and play it !!!! Some times also it do NOT work !!!

Any idea about sound for mobile games in HTML5 (without flash),or a best practice for fast calling for the element rather than document.getElementById ???


回答1:


I would recommend pre-defining an array that contains the pointers to the various audio elements before you call one (rather than repeat the document.getElementById('audioDiv').getElementsByTagName("audio") lookup multiple times Also make sure you have pre-loaded the audio samples so they are cached and you're not waiting on network resources the first time you need them

If you are working on an HTML5 based game I'd suggest you have a look at the EaselJS framework, especially the SoundJS pieces... http://www.createjs.com/#!/SoundJS



来源:https://stackoverflow.com/questions/14032412/faster-way-for-calling-audio-element-to-play-in-html5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!