Reputation: 6209
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.
Upvotes: 109
Views: 442964
Reputation: 1004
This is what I use with jQuery:
$('.button').on('click', function () {
var obj = document.createElement('audio');
obj.src = 'linktoyourfile.wav';
obj.play();
});
Upvotes: 6
Reputation: 784
What about:
$('#play').click(function() {
const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");
audio.play();
});
Upvotes: 14
Reputation: 2744
$("#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.
Upvotes: 69
Reputation: 5462
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()
.
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 .currentTime
above, to learn its length we use .duration
.
When the currentTime is equal to its duration audio file will stop playing. Whenever you use
play()
, it will start from the beginning.
timeupdate
event to update current time whenever audio .currentTime
changes.canplay
event to update information when file is ready to be played.$(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>
Upvotes: 173
Reputation: 345
I here have a nice and versatile solution with a fallback:
<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 many audio as you like:
<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 whereever you like with simple event calls like
onclick="clicksound.playclip()"
onmouseover="plopsound.playclip()"
Upvotes: 14
Reputation: 558
For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:
audio.mp3
for
http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
linking in a freely available mp3 off the web. Thank you for sharing the easy solution!
Upvotes: 24