7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
FREELessons: 11Length: 57 minutes

Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

2.3 Make Some Noise

In this lesson, I'll show you how to play sound in response to a button click.

2.3 Make Some Noise

Okay, now we're ready to have some fun. Let's add some sound to our site. We'll play a short sound to confirm that the user's transaction was successful. First, let's open our audio js file. As we learned earlier, in order to use the wave audio API to make any sound at all, we'll need an audio context. Let's create one right at the top here. We just say var context = new Audio context. The next thing to do, is write a playNote function. We'll use this to handle the playing of a musical note, using the Web Audio API. Okay, to make a noise we'll need an oscillator, which we'll make by saying var osc = context.create oscillator. Now oscillators by default are quite loud. The last thing we want to do is scare the living daylights out of our users. So we should turn the volume down a bit. To do this, the Wave Audio API provides a gain node, which allows us to decrease or increase the volume of the signal being passed to it To create this node, we write volume = context.createGain. We then have to set the gain value. This is the amount you want to multiply the volume going into the node by. We want to make it quieter, so we say volume.game.value equals 0.25. So what this does is it multiplies the incoming signal by 0.25. So that means the output volume of this node will be a quarter of the volume of the signal that's passed into it. So remember, like our electric guitarist from earlier, we need to take our leads to connect these two nodes. We do this by saying osc.connect(volume). We then want to connect our volume node to our speakers, which we do by writing volume.connect and we pass it context.destination. Okay that says all connected up. All we need to do now is to start the oscillator playing. We do that by saying, osc.start. And we want it to start as soon as the function's called so we pass it the current time. That's context.currentTime. And we'll want it to stop let's say, one second later. So we say osc.stop(context.currentTime) + 1). So basically, that's one second later from when this function was called. All we have to do now is call our playNode function. We want this to happen after fakeajax callback is fired, so let's put it in here. Okay, let's go over to the browser to try it out. Click refresh. Then click our button. [SOUND] Lovely. Well, not that lovely. It needs some art to make it sound a bit nicer, which luckily is what we're going to do in the next lesson.

Back to the top