Game Development Reference
In-Depth Information
One of the main challenges of integrating video and audio into browsers is the difference in codec
selections in different browsers, which requires us store several copies of content; for example, Ogg
Vorbis files for Firefox, Chrome, and Opera, and MP3 files for IE9 and Safari.
Let us take a closer look at cases of using <audio> . These are first, background music, and second, action
sounds. Each option has its pitfalls, with some browsers lacking the capability to loop music tracks;
whereas the single-channel nature of the sound prevents repeating the track before it ends.
We will talk about this single-channel nature of <audio> in more detail. It means that if we restart the file as
it is playing—for instance, when the player is shooting rapidly—the browser will cut off the sound and start
again. To prevent that sort of behavior, we can create several audio objects and rotate them, as shown in
Listing 10-3.
Listing 10-3. An example of implementing multi-channel sound by rotating audio elements
<audio id="sound_fire" src="audio/laser.wav" preload="auto"></audio>
<a href="javascript:play_multi_sound('sound_fire');">Fire</a><br />
<script>
var channel_max = 10; // number of channels
audiochannels = new Array();
for (a=0;a<channel_max ;a++)
{ // prepare the channels
audiochannels[a] = new Array();
audiochannels[a]['channel'] = new Audio(); // create a new audio object
audiochannels[a]['finished'] = -1; // expected end time for this channel
}
function play_multi_sound(s)
{
for (a=0;a<audiochannels.length;a++)
{
thistime = new Date();
if (audiochannels[a]['finished'] <thistime.getTime())
{
// is this channel finished?
audiochannels[a]['finished'] = thistime.getTime() +
document.getElementById(s).duration*1000;
audiochannels[a]['channel'].src = document.getElementById(s).src;
audiochannels[a]['channel'].load();
audiochannels[a]['channel'].play();
break;
}
}
}
</script>
The tag <audio> is relatively new, and there are a fairly large number of people still using browsers that do
not support it. Historical reference makes it clear that it is not always the optimum solution to fall back on
<object> , so the best option would be to use a compatible Flash object. One of the easiest ways to do this
is to employ an audio.js library to handle the problems.
 
Search WWH ::




Custom Search