//OUTPUT: Adding and playing audio

<New code>


Create an audio player with visible controls:

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

Create an audio player with invisible controls:

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

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">
        <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">


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

        <h4>Show me audio with no controls!</h4>
        <audio id="audioID">
            <source src="http://drapak.ca/cpg/beep.mp3" type="audio/mpeg">
        <h4>Trigger audio using javascript code!</h4>
        <button id="buttonID">Click me to beep!</button>
            //OUTPUT: play the beep sound
            var outputSound = function () {
                console.log( "in outputSound..." );
            //INPUT: play a sound whenever the button is pressed
            document.getElementById("buttonID").onclick = outputSound;

Learn more