2

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?

3
  • 1
    Did you mean to say you get an error stating 'audio.play' is not a function? I'm pretty sure it would be correct that 'alert.play' is not a function unless you specifically defined a new alert object with a play method. Commented Jun 16, 2011 at 2:41
  • Copy&Paste from Firefox Errorconsole: Error: audio.play is not a function - certainly a good point to ask, but sadly it's true o.O Commented Jun 16, 2011 at 2:45
  • 1
    That makes more sense - I assumed that's what you meant, but just wanted to be sure there wasn't a typo in your actual code. Commented Jun 16, 2011 at 2:47

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you :D - I could hit myself with something heavy right now, but it's a good feeling to have that thing finally running.
4

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.