Want to add some sound effects to your website or game? With HTML5, it’s easy! Here’s a quick tutorial. (If you have your soundbite already and want to get straight to the code, skip to step 4.)
You can Google around for the sound you want, but I would suggest signing up for a free sound effect library. I found freesound.org to be very helpful for finding those clicks, pops, and chimes. Alternatively, you can grab sounds from YouTube using an MP3 converter like this one. When you find the sound you want, download it.
For this, you’ll want a free, lightweight audio editor. Audacity is my recommendation. Download it, install it and fire it up. Import your soundbite.
Here’s the fun part. Zoom in really close, and trim off any dead space from the beginning of the sound. This subtle (or sometimes not-so-subtle) improvement will ultimately make your app feel more responsive and satisfying. Notice the straight line at the beginning of the example below. If you see that in your file, highlight it and press delete. Your soundbite is now ready for use.
Simply use Finder or Windows Explorer to move the freshly trimmed audio file into your app directory. If you will have multiple audio files, it is helpful to make a dedicated audio folder to keep things organized.
Add an audio element in your HTML file. This will not show up on the page, so you can put it anywhere. It simply needs to exist so you can reference it with jQuery. In our example, we are using a file called pop.wav.
<source src="audio/pop.wav" type="audio/mpeg">
(Note: If you want to add an audio player with play, pause, and volume controls, follow the below format. This will, of course, show up on the page.)
<source src="horse.mp3" type="audio/mpeg">
In your .js file, wherever you want your soundbite to play, use the following code:
$('audio#pop')uses jQuery to select all audio elements with an id of ‘pop’.
- This will return an array, so you need to specify the first element by adding .
.play()will play your soundbite.
Note: if you have a long soundbite, you can pause it by calling
.pause(). There is no “stop” function, so if you’d like it to restart from the beginning, call
.currentTime = 0 on another line.
Altogether, that looks like this:
$('audio#pop').currentTime = 0