How to Play Audio in jQuery

Sheeraz Gul Feb 02, 2024
How to Play Audio in jQuery

This tutorial demonstrates how to play audio using jQuery.

Play Audio Using jQuery

jQuery doesn’t provide built-in functionality to play audio, but we can use the HTML audio tag with jQuery to create a system for audio playing. We can manipulate the canplay event of the audio tag to use it whenever we want to play audio using jQuery.

Using jQuery, we can implement play, pause, restart and stop options for audio. Let’s create a system that can play, pause, restart and stop the audio using jQuery.

See the steps below:

  • First, the HTML part will only contain divs and buttons, not the audio element.
  • The audio element will be created by jQuery when the document is ready.
  • Once the audio element is created, we set its source attribute.
  • Set the value for the ended event. We made it play again when the audio was finished playing.
  • We implement tasks for the four buttons Play, Pause, Restart, and Stop.
  • For the Play and Pause buttons we can use the built-in play() and pause() methods.
  • For the Restart, we set the currentTime for the audio to 0. For the Stop, we set the currentTime for the audio to 0 and then use the pause() method.
  • Then, we use the event canplay to show the audio’s duration, source, and status.
  • Finally, we show the audio playing time using the time update event.

Let’s try to implement an example based on the above steps using jQuery:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Play Audio</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <style>
    #Demo {
    background-color : lightgreen;
    height: 50%;
    width:  100%;
    }
    #Main {
    border: 5px solid green;
    background-color : lightgreen;
    height: 10%;
    width:  20%;
}
    .DemoButton {
    font-size: 14px;
    font-weight: 500;
    line-height: 20px;
    list-style: none;
    cursor: pointer;
    display: inline-block;
    font-family: "Haas Grot Text R Web", "Helvetica Neue", Helvetica, Arial, sans-serif;
    margin: 0;
    padding: 10px 12px;
    text-align: center;
    background-color: rgba(51, 51, 51, 0.05);
    border-radius: 8px;
    border-width: 0;
    color: #333333;
    transition: all 200ms;
    vertical-align: baseline;
    white-space: nowrap;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}

    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>

</head>

<body>
<div id = "Main">

    <h2>Click to Play, Pause, Restart, Stop...</h2>
    <button class="DemoButton" id="ClickPlay">Play</button>
    <button class="DemoButton" id="ClickPause">Pause</button>
    <button class="DemoButton" id="ClickRestart">Restart</button>
    <button class="DemoButton" id="ClickStop">Stop</button>
    <hr>
    <h2>Audio Playing Time</h2>
    <div id="AudioRunningTime">0</div>
    <hr>
    <h2>Audio File Info</h2>
    <div id="AudioLength">Duration of Audio:</div>
    <div id="AudioSource">Source of the Audio:</div>
    <div id="AudioStatus" style="color:red;">Status: Click Play</div>

</div>
</body>

<script>

$(document).ready(function() {
    var DemoAudio = document.createElement('audio');
    DemoAudio.setAttribute('src', 'demo.mp3');

    DemoAudio.addEventListener('ended', function() {
        this.play();
    }, false);

    DemoAudio.addEventListener("canplay",function(){
        $("#AudioLength").text("Duration of Audio:" + DemoAudio.duration + " seconds");
        $("#AudioSource").text("Source of the Audio:" + DemoAudio.src);
        $("#AudioStatus").text("Status of Audio: Click Play").css("color","darkgreen");
    });

    DemoAudio.addEventListener("timeupdate",function(){
        $("#AudioRunningTime").text("Current second:" + DemoAudio.currentTime);
    });

    $('#ClickPlay').click(function() {
        DemoAudio.play();
        $("#AudioStatus").text("Status: Playing the Audio");
    });

    $('#ClickPause').click(function() {
        DemoAudio.pause();
        $("#AudioStatus").text("Status: Paused the Audio");
    });

    $('#ClickRestart').click(function() {
        DemoAudio.currentTime = 0;
    });
    $('#ClickStop').click(function() {
        DemoAudio.currentTime = 0;
        DemoAudio.pause();
        $("#AudioStatus").text("Status: Stop the Audio");

    });
});
</script>


</body>
</html>

The code above will play the audio given in the source, and we can play, pause, restart, and stop the audio anytime. See the output:

jQuery Play Audio

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook