Which approach?
You can play audio with
When document is ready we created an audio element dynamically
We set its source with the audio we want to play.
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.
We used timeupdate event to update current time whenever audio .currentTime changes.
We used canplay event to update information when file is ready to be played.
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;
});
});
Sound Information
Control Buttons
Playing Information
$(“#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.