We just launched our second project, A Generative Music Box. If you’ve ever played with the Bloom app on your iOS device, then you’ll have an idea of what you’re going to build: a graphic interface you can click on to generate sounds and graphics that combine to make a beautiful piece of ambient music.

We were inspired by Bloom, an iOS app created by Brian Eno and Peter Chilvers. It’s one of our favorite apps, and it’s a great way to explore some features in JavaScript including the canvas element, callback functions, setInterval, and the Web Audio API, as well as an opportunity to talk about strategies for organizing your code.

If you’ve never seen Bloom, here’s a short video showing the completed Music Box app in play:

As you can see, the way the application works is you click on the screen, which generates a sound, as well as a circle that grows, disappears and then repeats, along with the sound.

To create the sounds, we’re using the Web Audio API. We load MP3 samples into the browser using XMLHttpRequest with the “arraybuffer” type (used when you load binary data), and then use the AudioContext object that’s built-in to JavaScript to play the sounds.

The graphics are generated by programming the canvas element. When we get a click on the canvas we draw a circle and then animate the circle by repeatedly drawing the circle at larger sizes until we reach a maximum size.

One of the tricky details in this application is managing the timing of the sounds and the circles. As you’ll see when you do the project, we can handle this using setInterval and callback functions for both starting the sound and animation, and continuing the animation for a given period of time.

Unlike the previous project, which used one big JavaScript file for all the code, we split up the code for this project into multiple files, based on the purpose of the various components of the project. You’ll see how we use objects and functions to encapsulate behavior related to a specific feature of the application.

The reward for completing this project is a really fun app, that looks good and sounds good too. If you have basic HTML and CSS experience, and you’ve read Head First JavaScript Programming or you’ve had a bit of experience programming in JavaScript, you’ll have no problem tackling this project. So jump right in and give it a try.

Pin It on Pinterest

Share This

Give your Brain a Treat!

Don't miss out on brain-friendly updates, new WickedlySmart Projects, early access to books and general cool stuff! Just give us your email and we'll send you something about once a week. Don't worry, we'll never sell your name and you can remove yourself at any time.

Check your email to confirm your subscription.