I am trying to play an audio file when I click the button, but it’s not working, my html code is:
<html>
<body>
<div id="container">
<button id="play">
Play Music
</button>
</div>
</body>
</html>
my JavaScript is :
$('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 have created a Fiddle for that too.
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
canplayevent 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 exampleaudioElement.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
timeupdateevent to update current time whenever audio.currentTimechanges.canplayevent to update information when file is ready to be played.