View video tutorial

HTML Audio

HTML

The <audio> tag is used to play an audio file on a web page.

HTML Audio


<audio> tag uses <source> tag for audio files of alternate formats.

➔ The first recognized file will be played.

➔ The controls attribute adds media control buttons on the screen. such as play, pause, volume etc.

➔ If no files recognized by the browsers the text inside <audio> tags will be displayed.

HTML audio tag example

The HTML audio tag is used to include and play sound files on a webpage.



Note: Click play button to play the sound.

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML audio tag example</title>
    <style>
        .mydiv {
            border: 2px solid black;
            padding: 30px;
            background: rgb(100, 100, 100, 0.3);
            margin: 20px 0px;
        }
        input[type='submit'] {
            width: 120px;
            margin: 10px 0px;
            padding: 10px 20px;
            border-radius: 5px;
            background-color: #000;
            color: white;
            text-align: center;
        }
        input[type='submit']:hover {
            background-color: #f6f6f6;
            color: #000;
        }
    </style>
</head>
<body>
    <div id="div1" class="mydiv">
        <h3>HTML audio tag example</h3>
        <p>The HTML audio tag is used to include and play sound files on a webpage.</p>
        <audio id="myaudio" controls>
            <source
                src="resources/media/seaside.mp3" type="audio/mp3">
            This browser does not support the video tag.
        </audio><br><br>
        <input id="audioloop" type="submit" value="Loop" onclick="audiotoggleLoop()">
        <input id="audioplay" type="submit" value="Play" onclick="audioplaypause()">
        <input type="submit" value="Stop" onclick="audioStop()">
    </div>
</body>
<script>
    //for audio
    let myaudio = document.getElementById("myaudio");
    let audiobuttonLoop = document.getElementById("audioloop");
    let audiobuttonPlay = document.getElementById("audioplay");
    function audiotoggleLoop() {
        if (myaudio.loop) {
            myaudio.loop = false;
            audiobuttonLoop.value = "Loop Stopped";
        } else {
            myaudio.loop = true;
            audiobuttonLoop.value = "Loop Running";
        }
    }
    function audioplaypause() {
        if (myaudio.paused) {
            myaudio.play();
            audiobuttonPlay.value = "Pause"
        } else if (myaudio.play) {
            myaudio.pause();
            audiobuttonPlay.value = "Play";
        }
    }
    function audioStop() {
        myaudio.pause();
        myaudio.currentTime = 0;
        audiobuttonPlay.value = "Play";
    }
</script>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.