Adding Audio To Your App

I recently had a lot of fun building an audio based quiz app and thought I’d share how the audio was implemented.


<audio>

Using the HTML <audio> element is fairly straightforward. At a minimum, you need to define the src attribute, but other options include autoplay, controls, loop and muted. You can visist the MDN site for more details.

Arnie’s Game

For my app I built an Arnold Shwartzenegger quiz game that utilized several sound clips from his movies. Fun, right?! On page load I had Europe’s the Final Countdown play, where the music fades when the user clicks to start the game. Upon answering each question, a different Arnie audio clip is randomly generated depending on whether the answer is correct or incorrect. For some of my questions, playing a sound on button click provides a clue to the answer. Finally, depending on the user’s final score, Arnie tells you how you performed.

Implementing Audio

Given that each question has a unique audio answer, it makes sense that each question should have its <audio> element. However, a dryer approach when your assorted audio plays at different times is to use only one element. This was my approach and I have about 31 different audio clips. Using JavaScript for your audio controls, there isn’t a need for the controls attribute which displays those native to the browser. All you need to do is change the <src>attribute with every user action that triggers the audio response.

// HTML
<audio src="./assets/someAudio.mp3"></audio>// Vanilla JavaScriptlet audioElement = document.getElementById('audioID');
audio.setAttribute('src', './assets/newAudio.mp3');// JQuery$('.audioElementClass').attr('src', './assets/newAudio.mp3')[0].play();

Note: You will need additional audio elements if you intend to play multiple audio files simultaneously.

If you have a theme and want to play one of many sounds at random, you can do this using an array of src paths and grabbing one at random:

// 1. Array of audio source pathsconst arrayOfAudio = [
   "./assets/audio/audio1.mp3",
   "./assets/audio/audio2.mp3",
   "./assets/audio/audio3.mp3",
   "./assets/audio/audio4.mp3"
]// 2. Function to return a random value from an arrayrandomArrayValue = (array) => {
   return array[Math.floor(Math.random() * array.length)];
}// 3. Get random source path from the arrayconst randomAudioSource = randomArrayValue(arrayOfAudio);// 4. On a user event such as click or hover, set the attribute as described above.// 4a. Vanilla JavaScriptlet audioElement = document.getElementById('audioID');setSource = () => {
   setAttribute('src', './assets/newAudio.mp3');
}audio.onclick = setSource; // 4b. JQuery$('.buttonClass').on('click', function (e) {
   e.preventDefault();
   $('.audioElementClass').attr('src', './assets/newAudio.mp3')[0].play();

Audio onClick

When looking to play audio on button click, the element you use depends on the intended user experience. If you’d like your audio to restart every time the user clicks the button, use an <a> tag. Remember to prevent it’s default action like in the JQuery example above.

To prevent the audio from restarting on button click, use a <button> element.

Audio onPageLoad

Having audio play on page load is fairly straight forward. In Vanilla JavaScript you use the onload event handler and in JQuery you play the audio directly with the document.ready.

// Vanilla JavaScriptwindow.onload = function() {
   let audioElement = document.getElementById('audioID');
   audioElement.play();
}// JQuery$(document).ready(function() {
    $('#audioID').get(0).play();
});

If you’ve coded audio to play on page load, you might want to adjust the volume with a user event such as a button click. Adding this functionality is also pretty straight forward.

// Vanilla JavaScript - Volume runs from 0 to 1let audioElement = document.getElementById('audioID');
audioElement.volume = 0.5;// JQuery - Using the animation method for JQuery, you can control how long it takes for the volume to reach its end state. Time read in milliseconds.$('.audioElementClass').animate({ volume: 0 }, 1500);

Note: As of April 2018, Google Chrome’s new policy prevents audio files from playing on page load. You can setup the audio as suspended but you’ll need an event listener to resume it. Google’s documentation on this policy can be found here.