Learn creative coding writing simple programs

142. Processing.js with sound / audio (II)

This episode is special, as it is not about programming concepts in general, but about how to add sound to a processing.js program. You won't miss any important programming concepts if you skip it.

In Part II, we connect Processing.js with JavaScript. By adding some code in our Processing program, and in our html template, we are able to call JavaScript functions from Processing. Why would we want to do that? Since Processing.js does not directly play sound, we want to use JavaScript to play sound. That means that our program must somehow execute JavaScript code to play sound. By reading part of the Pomax Guide, we discover how to do that.

In the Processing side, we add an "interface", which is a object oriented concept which we may study in the future. For now, you should know that inside the "interface" block we must declare the functions we plan to call in the JavaScript side. In our example it's just two functions, to play two different sounds.

Currently in my Chromium browser in Ubuntu, the sounds play only once. I noticed I could fix this by calling .load() on the sounds before playing them. I hope this is solved in the future, as calling .load() sounds not very efficient. You can try what happens if you remove the .load() lines.

The files from this episode can be found at: https://github.com/hamoid/Fun-Programming/tree/master/processing/06/e141_pjs_audio

Challenge: make changes to the program so instead of two functions to play two sounds, you use just one function, and send the sound ID as an argument. Instead of playSound0() and playSound1(), use playSound(0) and playSound(1).

Tags: pjs, audio, sound

Code editor

You can make changes to the code below. Then

Questions and comments

Try to stay close to the topic of this episode. Use the Processing forums for help with unrelated Processing projects (or hire me for help ;-)

To indicate that a word in your comment is code, use the `backtick`. Example
Do `float` and `int` smell similar?
To highlight code blocks, surround it with ``` code-fences ``` like this:
``` void setup() { size(600, 600); } ```