Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

$(document).ready(function() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');
    
    audioElement.addEventListener('ended', function() {
        this.play();
    }, false);
    
    audioElement.addEventListener("canplay",function(){
        $("#length").text("Duration:" + audioElement.duration + " seconds");
        $("#source").text("Source:" + audioElement.src);
        $("#status").text("Status: Ready to play").css("color","green");
    });
    
    audioElement.addEventListener("timeupdate",function(){
        $("#currentTime").text("Current second:" + audioElement.currentTime);
    });
    
    $('#play').click(function() {
        audioElement.play();
        $("#status").text("Status: Playing");
    });
    
    $('#pause').click(function() {
        audioElement.pause();
        $("#status").text("Status: Paused");
    });
    
    $('#restart').click(function() {
        audioElement.currentTime = 0;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Sound Information</h2>
    <div id="length">Duration:</div>
    <div id="source">Source:</div>
    <div id="status" style="color:red;">Status: Loading</div>
    <hr>
    <h2>Control Buttons</h2>
    <button id="play">Play</button>
    <button id="pause">Pause</button>
    <button id="restart">Restart</button>
    <hr>
    <h2>Playing Information</h2>
    <div id="currentTime">0</div>
</body>

Answer from Ahmet Can Güven on Stack Overflow
Top answer
1 of 7
172

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

$(document).ready(function() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');
    
    audioElement.addEventListener('ended', function() {
        this.play();
    }, false);
    
    audioElement.addEventListener("canplay",function(){
        $("#length").text("Duration:" + audioElement.duration + " seconds");
        $("#source").text("Source:" + audioElement.src);
        $("#status").text("Status: Ready to play").css("color","green");
    });
    
    audioElement.addEventListener("timeupdate",function(){
        $("#currentTime").text("Current second:" + audioElement.currentTime);
    });
    
    $('#play').click(function() {
        audioElement.play();
        $("#status").text("Status: Playing");
    });
    
    $('#pause').click(function() {
        audioElement.pause();
        $("#status").text("Status: Paused");
    });
    
    $('#restart').click(function() {
        audioElement.currentTime = 0;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Sound Information</h2>
    <div id="length">Duration:</div>
    <div id="source">Source:</div>
    <div id="status" style="color:red;">Status: Loading</div>
    <hr>
    <h2>Control Buttons</h2>
    <button id="play">Play</button>
    <button id="pause">Pause</button>
    <button id="restart">Restart</button>
    <hr>
    <h2>Playing Information</h2>
    <div id="currentTime">0</div>
</body>

2 of 7
69
$("#myAudioElement")[0].play();

It doesn't work with $("#myAudioElement").play() like you would expect. The official reason is that incorporating it into jQuery would add a play() method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement"), aka 0.

This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":

To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.

🌐
Medium
medium.com › @ericschwartz7 › adding-audio-to-your-app-with-jquery-fa96b99dfa97
Adding Audio to Your App with jQuery | by Eric Schwartz | Medium
January 31, 2017 - $('audio#pop')[0].play() $('audio#pop') uses jQuery to select all audio elements with an id of ‘pop’. This will return an array, so you need to specify the first element by adding [0] . Finally, .play() will play your soundbite.
🌐
Team Treehouse
teamtreehouse.com › community › how-do-i-add-a-sound-when-a-button-is-clicked-jquery
How do I add a sound when a button is clicked? - jQuery (Example) | Treehouse Community
October 18, 2017 - <audio id="mysoundclip" preload="auto"> <source src="./assets/audio/ONEDICE.WAV"> </source> </audio> //create a diceroll event $('#dice-button').on('click', function(){ diceRoll(); $('#dice-div').html(randomNumber); //dice roll sound var audio = $("#mysoundclip")[0]; audio.play(); })
🌐
Jquery
forum.jquery.com › portal › en › community › topic › detect-if-html5-audio-is-playing-using-jquery
Detect if HTML5 audio is playing using JQuery
The HTML5 audio tag has a "paused" boolean property, it seems. I don't know where to start on harnessing it and using JQuery. I've read a few other results online similar to my problem but none of them worked or worked properly, including setting cookies. I'm sure the problem seems simple to more experienced designers like yourselves and I'd like to learn what's going on. Thank you. ... The side benefit of using the jQuery on for the play and pause events is that the buttons change when the audio is over, is paused, or never started (maybe an old browser that didn’t support mp3)
🌐
W3Schools
w3schools.com › jsref › met_audio_play.asp
HTML DOM Audio play() Method
Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio). ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Designmodo
designmodo.com › home › resources › coding › how to create an audio player in jquery, html5 & css3
How to Create an Audio Player in jQuery, HTML5 & CSS3
July 9, 2024 - MediaElement.js is a HTML5 audio and video player that also works for older browsers using Flash and Silverlight to mimic the HTML5 MediaElement API. ... First we need to download the “MediaElement.js” script and extract it. Then from the “build” folder we need three files: ... Then copy all these three files to the same directory, I will copy for my “js” folder. Now, we need to link to the jQuery Library, we can host it locally or use the one hosted by Google.
Find elsewhere
🌐
Thegreatcodeadventure
thegreatcodeadventure.com › rendering-and-playing-audio-files-with-html5-and-jquery
Rendering and playing audio files with HTML5 and Jquery
March 30, 2015 - If the result is "Yes", it used the .trigger("play") jquery method to play the audio file with an id of 'yes-audio'. If it the result is "Nope", we will play the audio file with an id of 'no-audio'.
🌐
Sololearn
sololearn.com › en › Discuss › 371844 › how-to-make-a-jquery-button-that-on-clicking-plays-audio
How to make a jquery button that on clicking plays audio | Sololearn: Learn to code for FREE!
<body> <button id="btn" type="button">Click here for sound</button> <audio id="audio" src="example.mp3"></audio> <script> //option 1 $("#btn").on("click", function() { var audio = $("#audio")[0]; audio.play(); }); // option 2 $("#btn").on("click", ...
🌐
Reddit
reddit.com › r/learnjavascript › i am fetching an audio file with jquery and i can console.log() the file as it's now stored in a variable. how can i play this audio in browser?
I am fetching an audio file with jQuery and I can console. ...
November 26, 2019 -

Here is my code snippet:

jQuery.get('<URL>', function(data) {
		console.log(data);
        //here I want to play this media file..
});

I am learning about buffers and it's probably the right way to go but I am so close to solving my immediate problem. The console.log output displays a bunch of output like this:

.. �J���'ķ�Hɴ (I�2=��n���$wv����5����Z�K��l[�jgJ�R�}'p`�F��?�a

..

So this must be the binary data of my audio file right? If I visit <URL> directly my browser detects it's an audio file and starts playback. Any help would be greatly appreciated!

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › HTMLAudioElement › Audio
HTMLAudioElement: Audio() constructor - Web APIs | MDN
An optional string containing the URL of an audio file to be associated with the new audio element. A new HTMLAudioElement object, configured to be used for playing back the audio from the file specified by url. The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given.
🌐
IAS
iasonline.org › home
IAS: The International Accreditation Service
February 11, 2026 - IAS is a nonprofit, public-benefit corporation that help organizations demonstrate compliance and competence to their customers, regulators and the public.
🌐
Programming Head
programminghead.com › how-to-play-audio-in-html-using-javascript
How to Play Audio in HTML using JavaScript | Audio Player
If you don't like to use HTML onClick ... Click. JavaScript's addEventListener will monitor any Click on the Selected HTML Element. If someone clicks the Selected HTML Element (Like Button). This will Play the HTML Audio....
🌐
Catholicchurchofphila
catholicchurchofphila.org › home
Home - Archdiocese of Philadelphia
May 22, 2025 - No matter how long or why you’ve been away, Jesus’ greatest desire is to welcome you home with love and compassion · Serve your community and deepen your faith by volunteering, joining a ministry, or discerning a call to the priesthood
🌐
KIRUPA
kirupa.com › html5 › playing_sound_audio_element.htm
Playing Sounds Using the Audio Element
Using plain vanilla-flavored JavaScript, create a simple (and awesome) audio player.
🌐
Brittany Chiang
brittanychiang.com
Brittany Chiang
jQuery · View Full Résumé · Video course that teaches how to build a web app with the Spotify Web API. Topics covered include the principles of REST APIs, user auth flows, Node, Express, React, Styled Components, and more. Web app for visualizing personalized Spotify data. View your top artists, top tracks, recently played tracks, and detailed audio information about each track.
🌐
InfoQ
infoq.com › news › 2026 › 02 › quesma-otel-bench-performance-ai
Quesma Releases OTelBench to Evaluate OpenTelemetry Infrastructure and AI Performance - InfoQ
February 24, 2026 - Audio ready to play · Your browser does not support the audio element. 0:00 · 0:00 · Normal1.25x1.5x Like · Reading list ·
🌐
Videojs
videojs.org
Video.js | Open Source Video Player
import { createPlayer } from '@videojs/react'; import { VideoSkin, Video, videoFeatures } from '@videojs/react/video'; import '@videojs/react/video/skin.css'; const Player = createPlayer({ features: videoFeatures }); export function VideoPlayer() { return ( <Player.Provider> <VideoSkin poster="https://image.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/thumbnail.webp"> <Video src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/highest.mp4" playsInline /> </VideoSkin> </Player.Provider> ); }
🌐
Driveinusa
driveinusa.com
New Movies at Stars and Stripes Drive-in Movie Theater - Enjoy the Freedom!
jQuery Carousel · 5101 Clovis Hwy. Lubbock, TX 79416 · 1178 Kroesche Ln.