//OUTPUT: Adding and playing audio

<New code>

//HTML:

//creates an audio player with full controls
<audio controls>
  <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
</audio>

//creates an invisible audio player with full controls
<audio id="audioBeepID">
  <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
</audio>

js //OUTPUT: document.getElementById('audioBeepID').play();
— plays a sound linked inside an audio tag with #audioBeepID

Audio can be as important as visuals

Audio can be a great addition to a program, especially games. But be careful! Unwanted audio can really irritate people.

As well, when you are developing programs you should be respectful of the people around you.

Class rule: you can only include sound in your programs if you use headphones or earbuds while working.

Code example

Show me audio with controls!

Show me audio with no controls!

Trigger audio using javascript code!

...is made with the following code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Adding and playing audio</title>
        <meta name="description" content="Learn how to add and play audio">
        <meta name="author" content="Dave Drapak">

        <script>
            //OUTPUT: play the beep sound
            var outputBeep = function () {
                document.getElementById("audioBeepID").play();
            }
        </script>
    </head>

    <body>
        <h4>Show me audio with controls!</h4>
        <audio controls>
            <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
        </audio>

        <h4>Show me audio with no controls!</h4>
        <audio id="audioBeepID">
            <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
        </audio>
        
        <h4>Trigger audio using javascript code!</h4>
        <button onclick="outputBeep();">Click me to beep!</button>
    </body>
</html>

Learn more