//OUTPUT: Adding and playing audio

<New code>

//HTML:

Create an audio player with visible controls:

<audio controls>
  <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
</audio>

Create an audio player with invisible 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">

    </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="audioID">
            <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
        </audio>
        
        <h4>Trigger audio using javascript code!</h4>
        <button id="buttonID">Click me to beep!</button>
        
        <script>
            //OUTPUT: play the beep sound
            var outputSound = function () {
                console.log( "in outputSound..." );
                
                document.getElementById("audioID").play();
            }
            
            //INPUT: play a sound whenever the button is pressed
            document.getElementById("buttonID").onclick = outputSound;
        </script>
    </body>
</html>

Learn more