Creating your first sound with the Web Audio API
Ever since I started to code I’ve wanted to learn about the browser’s Web Audio API. My long term goal is to create a full synthesizer with it, so give me a follow if you want to watch me on that journey.
I remember during my last few weeks at Flatiron School I was experimenting a bit with the Web Audio API and was able to create a sound in the browser. I want to show you how simple something like this can be.
The Web Audio API
According to MDN, the Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.
You can easily see how vast of an API this is. However, getting started with it is as simple as a whistle.
In order for us to create a sound in our web browser, we need the establish the most important part of our Web Audio API, the AudioContext.
let context = new AudioContext()
In order for us to access the Web Audio API, we need to create a new AudioContext(). This is very similar to creating a new HTML canvas. The next thing we need is to create an Oscillator to create our sound. An oscillator, for the uninitiated, is a circuit which produces a continuous, repeated, alternating waveform without any input. These waveforms are sound waves. I’ll get into those in a later blog.
let oscillator = context.createOscillator()oscillator.connect(context.destination)
Here we’re creating our oscillator with the Web Audio API’s createOscillator() method. Once we have it, we must connect it to our Audio Context by sending it to our destination. If you want any sort of sound to exist in your browser, your audio context needs and oscillator and to connect to a destination.
Once you have the above code, all you need to do to create your first sound is to call oscillator.start(). If you load your page on the browser now, you should have a sound!
If you hear that sound, you’re doing great! But that sound is going on, and on, and on…really annoying, right? Well, all we need to do is set a timeout with setTimeout and call oscillator.stop() and add a value of time to this function. Now we have a sound that lasts 5 seconds.
If your sound didn’t play, you might have seen an error in your console that looked like this:
That means you need to create a button or an event to start the sound. Your browser has a security measure in it that makes a user need to do a gesture before any sounds will play using the Web Audio API. So after cleaning that up you’re code could look something like this…
Enjoy your sound making button! I’m going to learn more about how to change our sounds and write a new blog soon!