Play an Audio File Using Jquery When a Button Is Clicked

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 .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. 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.


  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. 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



Leave a reply



Submit