DEV Community

Matthew Odle
Matthew Odle

Posted on

3 1

Handling Sounds With HTML5 Canvas

There are two takeaways here: initialize assets and reuse them, and if you want to play event-triggered sounds that could overlap (laser firing, for example), you'll want multiple copies of the asset available.

I learned pretty early to initialize static assets once and then reuse them. The original implementation was adding a new asset for each game object. This meant every laser fired would add another sound to the DOM. As you can imagine, this allows you to figure out the upper limit on the quantity of elements in the DOM pretty quickly.

The solution was to not tie the sounds directly to objects, but rather to create a pool of sounds, then cycle through the pool when a sound was triggered.

Here is the implementation:

https://github.com/modle/centipede/blob/260fa54dadce91f25148638cf1eb10d46ff13dec/app/scripts/sound.js

init() will get called by the loader script, and will loop on the keys of the tracks object, creating the sounds and adding them to the DOM.

To play the sound, we just call playSound() with the type matching the key we want. playSound() will call getSound(), which will use mod to set the target index to the next index, or 0 if previous index was the end of the array. Then the sound element at that index will get returned and played.

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video 📺

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay