Play an audio file using jQuery when a button is clicked
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 .currentTime
above, to learn its length we use .duration
.
Example Guide
- 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 useplay()
, 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; });});
<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>
jQuery play audio by selector
You need to use .play()
to trigger the audio, and use $(selector).get(0)
to get the audio object.
$('button').click(function(){
if ( true ) {
$('.sound1').get(0).play();
} else {
$('.sound2').get(0).play();
}
});
Demo (Toggle true / false
to hear .wav
and .mp3
file)
Audio Credits
How to play audio when a button is pressed?
This will work best acc. to your use case.
const btn = document.getElementById("btn");
btn.onclick = () => {
// Here you will add path to local file you have
const audio = new Audio(
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
);
audio.play();
};
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="btn">Play Sound</button>
</div>
<script src="src/index.js"></script>
</body>
</html>
How do I play an audio file with jQuery?
You forgot the hash #
in your ID selector :
var buzzer = $('#buzzer')[0];
$(document).on('submit', '#sample', function() {
buzzer.play();
return false;
});
And document.getElementById('buzzer')
does seem more appropriate!
I'd change the HTML to:
<audio id="buzzer" src="buzzer.ogg" type="audio/ogg"></audio>
<input type="button" value="Start" id="start" />
and do:
$('#start').on('click', function() {
$('#buzzer').get(0).play();
});
Playing sound after jquery onclick
You can use .each()
to iterate all .audio
element, set currentTime
to 0
, call .pause()
; then call .load()
, .play()
on event.target
:var audio = $(this)[0];
. Note, document
is an object, not a string
$(document).ready(function () {
var elems = $(".audio");
elems.click(function (event) {
elems.find("audio").each(function() {
this.pause();
this.currentTime = 0;
});
console.log("Event triggered");
var audio = $(this).find("audio")[0];
audio.load();
audio.play();
});
});
Stopping audio when another audio file is clicked using jQuery while obscuring link
I imagine something like this:
$(".play").on('click',function(){
var key = $(this).attr('key');
EvalSound(key);
});
var thissound = new Audio();
var currentKey;
function EvalSound(key) {
if(currentKey !== key)
thissound.src = "http://designlab360.org/fhi/splash/dev2/audio/" + key + ".mp3";
currentKey = key;
if (thissound.paused)
thissound.play();
else
thissound.pause();
thissound.currentTime = 0;
currentPlayer = thissound;
}
See http://jsfiddle.net/sjmcpherso/pt3cx1eo/11/
Playing audio file on click again before it's finished playing
Try moving your variables inside your click handlers, so that you create a new Audio
element every time one of your buttons is clicked.
$(document).ready(function(){
$(".kickbass1").click(function(){
var kickBass1 = new Audio("audio/kickbass1.mp3");
kickBass1.play();
});
$(".hihat1").click(function(){
var hihat1 = new Audio("audio/hihat1.mp3");
hihat1.play();
});
$(".snare1").click(function(){
var snare1 = new Audio("audio/snare1.mp3");
snare1.play();
});
});
Related Topics
Intercept a Form Submit in JavaScript and Prevent Normal Submission
How to Parse HTML in Google Apps Script
Html5 Canvas Drawimage Ratio Bug Ios
React Js Conditionally Applying Class Attributes
Equivalent of Jquery .Hide() to Set Visibility: Hidden
How to Stretch Images With No Antialiasing
What Is the Explicit Promise Construction Antipattern and How to Avoid It
Accessing Nested JavaScript Objects and Arrays by String Path
How to Use Sockets in JavaScript\Html
JavaScript Data Grid For Millions of Rows
How to Show a Hidden Div When a Select Option Is Selected
Positioning ≪Div≫ Element At Center of Screen
Is It Possible For Flex Items to Align Tightly to the Items Above Them
How to Transform Black into Any Given Color Using Only CSS Filters
How to Make the Browser Wait to Display the Page Until It's Fully Loaded
JavaScript: Find Div'S Line-Height, Not CSS Property But Actual Line-Height