Fiona Runge
Fiona Runge

Reputation: 2311

Using Javascript to play an audioelement (html5)

I'm trying to figure out how to trigger playing an audio from javascript. I got some html which looks like:

<div class='audio' >foo
<audio preload='auto' controls src='test.wav'>
<b>Your browser does not support the audio tag.</b>
</audio>
</div>

And I'm trying to trigger it with:

$(document).ready(function () {
    $('.audio').each(function(){
        var audio = $(this).find('audio').get();
        $(this).click(function(){
            audio.volume = 100;
            alert('1 '+audio);
            audio.play();
            alert('2');
        });
    });
});

alert('1 '+audio); works as expected and reports audio as HTMLAudioElement. However alert('2'); is not called because I get the error 'audio.play' is not a function. What can I do to solve this problem?

Upvotes: 2

Views: 8888

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Your code looks perfect. What is the error you are getting is it "alert.play" is not a function or "audio.play" is not a function.

I think

var audio = $(this).find('audio').get();

returns an array try this

var audio = $(this).find('audio').get(0);

Upvotes: 7

auco
auco

Reputation: 9579

Controlling audio without jQuery using just JavaScript is even easier if you give the audio tag an ID:

<audio id="myAudioTagID" type="audio/mpeg" src="sound.mp3"></audio>

then you can simply get the element and apply .pause(), .start(), stop() :

var audio = document.getElementById("myAudioTagID");
audio.play();
audio.pause();
audio.stop();

Upvotes: 4

Related Questions