Play an audio file using jQuery when a button is clicked

I am trying to play an audio file when I press a button, but it does not work, my html code is:

<html> <body> <div id="container"> <button id="play"> Play Music </button> </div> </body> </html> 

my javascript:

 $('document').ready(function () { $('#play').click(function () { var audio = {}; audio["walk"] = new Audio(); audio["walk"].src = "http://www.rangde.org/static/bell-ring-01.mp3" audio["walk"].addEventListener('load', function () { audio["walk"].play(); }); }); }); 

I created a fiddle for this.

+85
javascript jquery html
Dec 13 '11 at 13:02
source share
5 answers

Which approach?

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

What we used

We will use the canplay event to find that our file is ready to play.

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

We can find out the length of the audio file and the current playback time. We have already studied .currentTime above to find out its length, we use .duration .

Leadership example

  • When the document is ready, we created a dynamic element dynamically
  • We set the sound source that we want to play.
  • We used the "ended" event to run the file again.

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

  1. We used the timeupdate event to update the current time when the .currentTime sound .currentTime .
  2. We used the canplay event to update information when the file is ready to play.
  3. We created buttons for 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> 
+137
Dec 13 '11 at 13:09
source share

Actual answer in jQuery:

 $("#myAudioElement")[0].play(); 

It does not work with $("#myAudioElement").play() as you would expect. The official reason is that including it in jQuery will add the play() method to each individual element, which will lead to unnecessary overhead. So instead, you should reference it by its position in the array of DOM elements that you $("#myAudioElement") with $("#myAudioElement") , otherwise 0.

This quote is taken from an error message that was closed as "feature / wontfix":

To do this, we need to add the jQuery method name for each method name of the DOM element. And, of course, this method will not do anything for non-media items, so it does not look like it will cost the extra bytes that are required.

+38
Jul 23 '16 at 22:43
source share

For someone else following me, I just opened Ahmet and updated the original jsfiddle request here , substituting:

 audio.mp3 

for

 http://www.uscis.gov/files/nativedocuments/Track%2093.mp3 

connecting in freely available mp3 from the internet. Thank you for getting a simple solution!

+21
Jan 28 '13 at 20:23
source share

I have a nice and universal rollback solution:

 <script type="text/javascript"> var audiotypes={ "mp3": "audio/mpeg", "mp4": "audio/mp4", "ogg": "audio/ogg", "wav": "audio/wav" } function ss_soundbits(sound){ var audio_element = document.createElement('audio') if (audio_element.canPlayType){ for (var i=0; i<arguments.length; i++){ var source_element = document.createElement('source') source_element.setAttribute('src', arguments[i]) if (arguments[i].match(/\.(\w+)$/i)) source_element.setAttribute('type', audiotypes[RegExp.$1]) audio_element.appendChild(source_element) } audio_element.load() audio_element.playclip=function(){ audio_element.pause() audio_element.currentTime=0 audio_element.play() } return audio_element } } </script> 

After that, you can initialize as much audio as you want:

 <script type="text/javascript" > var clicksound = ss_soundbits('your/path/to/click.ogg', "your/path/to/click.mp3"); var plopsound = ss_soundbits('your/path/to/plopp.ogg', "your/path/to/plopp.mp3"); </script> 

Now you can reach the initialized audio element, if you want, with simple event calls such as

 onclick="clicksound.playclip()" onmouseover="plopsound.playclip()" 
+11
Jul 09 '14 at 14:45
source share

If this helps you in 2019, then you should know that I am creating a jquery / Zepto plugin. You can download it here: https://github.com/xpectmore/simple-jquery-audio-play-button

It is under the A-FREE-to-MANKIND license a very simple material.

0
Apr 26 '19 at 13:40
source share



All Articles