Audio

HTML5 supports the mp3, wav and ogg file formats. The <audio> tag is used to hold music.

The 'contols' parameter causes an audio control dashboard to display in the webpage.

<audio src = 'mySoundFile.mp3' controls>

Add the autoplay parameter to automatically play an audio clip.

<audio src = 'mySoundFile.mp3' controls autoplay>

Add the loop parameter to automatically play an audio clip.

<audio src = 'mySoundFile.mp3' controls autoplay loop>

Encapsulate the audio inside <audio></audio> tags to deal with older browsers that do not support the <audio> tag

<audio src = 'mySoundFile.mp3'>

<p>Your browser does not support the 'audio' tag </p>
</audio>

Example of a HTML5 audio player (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>Course notes example code</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <audio src = './audio/audio01.mp3' controls autoplay>
            <p>Your browser does not support the '<audio>' tag </p>
        </audio>
    </body>
</html>

Replace the song in the example above with a different song.

Audio Javascript Support

Add an id parameter so that you can control the audio using JavaScript.

<audio id = 'myAudioClip' src = 'mySoundFile.mp3'>

You can use the javascript getElementById() to access the audio player. You can play, pause and stop play for an audio clip.

 

The code below will seek to a particular second within an audio clip.

document.getElementById('mediaElementID').currentTime = 30;  // seek to 30 seconds

The code below will get the length of an audioclip, in seconds.

document.getElementById('mediaElementID').seekable.end(0); // number of seconds in audio clip

The code below will return the number of seconds that have been played so far in an audioclip.

document.getElementById('mediaElementID').currentPosition;

Example of a Javascript controlled audio player (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>Course notes example code</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <script>
            let mediaClip; // shortcut for document.getElementById('mediaClip')

            function init()
            {
                // initialise the mediaClip variable  
                mediaClip = document.getElementById('mediaClip');

                // get the length of the audio clip
                document.getElementById('clipDuration').innerHTML = 'Length:' + Math.floor(mediaClip.seekable.end(0) / 60) + ':' + twoDigits(Math.floor(mediaClip.seekable.end(0) % 60));

                mediaClip.addEventListener("volumechange", mediaClipVolumeChangeHandler);
                mediaClipVolumeChangeHandler(); // call first time to set volume display data


                mediaClip.addEventListener("timeupdate", mediaClipTimeUpdateHandler);
                mediaClipTimeUpdateHandler(); // call first time to set time display data                
            }

            function playClip()
            {
                document.getElementById('mediaClip').play();
            }

            function pauseClip()
            {
                document.getElementById('mediaClip').pause();
            }

            function stopClip()
            {
                // There is no stop function.
                // Instead, we pause and set the currentTime to 0
                document.getElementById('mediaClip').pause();
                document.getElementById('mediaClip').currentTime = 0;
            }

            function decreaseVolume()
            {
                // minimum volume is 0  
                if (mediaClip.volume > 0)
                {
                    mediaClip.volume -= 0.01;
                }
            }

            function increaseVolume()
            {
                // maximum volume is 1
                if (mediaClip.volume < 1)
                {
                    mediaClip.volume += 0.01;
                }
            }

            function toggleMute()
            {
                if (mediaClip.muted)
                {
                    mediaClip.muted = false;
                }
                else
                {
                    mediaClip.muted = true;
                }
            }

            function toggleControls()
            {
                if (mediaClip.controls)
                {
                    mediaClip.controls = false;
                }
                else
                {
                    mediaClip.controls = true;
                }
            }

            function Goto15Secs()
            {
                mediaClip.currentTime = 15;
            }

            function twoDigits(number)
            {
                if (number < 10)
                {
                    number = ("0" + number).slice(-2);
                }
                return number;
            }

            function mediaClipVolumeChangeHandler()
            {
                // update the current volume
                if (mediaClip.muted)
                {
                    document.getElementById('currentVolume').innerHTML = 'Volume:MUTED';
                }
                else
                {
                    document.getElementById('currentVolume').innerHTML = 'Volume:' + Math.floor(mediaClip.volume * 100);
                }
            }

            function mediaClipTimeUpdateHandler()
            {
                document.getElementById('currentPosition').innerHTML = 'Current Position:' + Math.floor(mediaClip.currentTime / 60) + ':' + twoDigits(Math.floor(mediaClip.currentTime % 60));

            }
        </script>
    </head>

    <body onload = 'init()'>
        <audio id = 'mediaClip' controls src = './audio/audio03.mp3'>  
            <p>Your browser does not support the 'audio' tag </p>
        </audio>

        <br>
        <button onclick = 'playClip()'>Play</button>
        <button onclick = 'pauseClip()'>Pause</button>
        <button onclick = 'stopClip()'>Stop</button>
        <br>
        <button onclick = 'decreaseVolume()'>Decrease Volume</button>
        <button onclick = 'increaseVolume()'>Increase Volume</button>
        <button onclick = 'toggleMute()'>Toggle Mute</button>
        <br>
        <button onclick = 'toggleControls()'>Toggle Controls</button>
        <br>
        <button onclick = 'Goto15Secs()'>Goto 15 Seconds</button>

        <p id='clipDuration'></p>
        <p id='currentPosition'></p>
        <p id='currentVolume'></p>
    </body>
</html>

Use sliders to adjust the volume in the example above, as shown here.

Replace the Play and Pause buttons with a single Play/Pause button in the example above, as shown here.

Restrict Audio Playback Time Range

The playback time range can be restricted by adding time parameters to the source file, as shown below.

Example of restricted playback timerange, which plays from the 65 second to the 68 second (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>Course notes example code</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <audio src = './audio/audio02.mp3#t=65,68' controls autoplay>
            <p>Your browser does not support the 'audio' tag </p>
        </audio>
    </body>
</html>

Note that spaces are not allowed in the #t=65,68

Other time range options are:

#t=65                    // play from the 65 second until the end
#t=,68.5                 // play from the start until the 68.5 second
#t=00:01:05,00:01:08     // play from the 65 second until the 68 second

Add a click sound of duration 0.1 seconds when a button is pressed. (solution)

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>