Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I play an audio file with jQuery?

I'm having a difficult time getting audio to work with jQuery. I've tried this with both .wav and .ogg formats. (Firefox 19.0.2)

Clicking the Start button yields:

TypeError: buzzer.play is not a function

I'm not sure if jQuery selectors return an array, but I've tried the capture the audio file with both:

var buzzer = $('buzzer');

and

var buzzer = $('buzzer')[0]; 

Regardless, I can't get the audio elements to play.

<!DOCTYPE html>     
<html>     
    <head>      
    <meta name="viewport" content="width=device-width, initial-scale=1">     
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>    
</head>     

<body>     

<audio id="buzzer" src="buzzer.ogg" type="audio/ogg">Your browser does not support the &#60;audio&#62; element.</audio>    
<form id='sample' action="#" data-ajax="false">    
    <fieldset>    
     <input value="Start" type="submit">    
     </fieldset>    
</form>    
<script type="text/javascript">    

var buzzer = $('buzzer')[0];    

$(document).on('submit', '#sample', function()  {     
    buzzer.play();    
    return false;    
});    

</script>    
</body>    
</html>  
like image 369
BryanWheelock Avatar asked Apr 08 '13 20:04

BryanWheelock


People also ask

How do I make audio play in JavaScript?

play() to Play Audio Files in JavaScript. We can load an audio file in JavaScript simply by creating an audio object instance, i.e. using new Audio() . After an audio file is loaded, we can play it using the . play() function.

Can I play audio in HTML?

The HTML <audio> element is used to play an audio file on a web page.

How you can use JavaScript to play the sound for the button Colour?

Hello everyone, In this post, we will examine how to solve the How You Can Use Javascript To Play The Sound For The Button Color Selected problem using the computer language. var audio = new Audio("play. mp3"); audio. play();


2 Answers

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();
});
like image 182
adeneo Avatar answered Oct 12 '22 13:10

adeneo


var buzzer = document.getElementById("buzzer");

You can also do this:

var buzzer = $('audio')[0]; 

And if id buzzer is unique (As it should) you can also do this - no need of [0]

var buzzer = $('#buzzer');
like image 24
Mohammad Adil Avatar answered Oct 12 '22 14:10

Mohammad Adil