Iteration #1: Playing Sounds Using a Single Object

We just described the first iteration of the dynamic audio code. It works by attempting to call the play() function of both shootSound and explodeSound as often as necessary. This appears to work at first, but if you listen carefully (and this is apparent on some browsers more than others), the sounds start to play “off,” or not play at all. This is because we are using a single object and attempting to play and replay the same sound over and over. A single HTMLAudioElement was not designed to operate this way. You can test this example in the code distribution by running CH7EX6.html in your HTML5-compliant web browser. Press the fire button as quickly as possible, and listen to when and how the sounds play. After a bit, they start to play at the wrong time, don’t finish, or don’t play at all. Figure 7-7 shows what the first iteration of Space Raiders looks like in a web browser.

Space Raiders playing sounds from two objects

Figure 7-7. Space Raiders playing sounds from two objects

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.