May 11, 2012

Javascript method pause() only works with audio element

Question by Panini Venkataraman

So I have a function like this:

function music(song) {
var audio = new Audio("audio/" + song + ".ogg");
audio.play();
}

And the problem I’m having is that audio.play() works perfectly, but if I try audio.pause() later (after defining the same variable), it doesn’t work. However, if I do this:

function music() {
var audio = document.getElementById("songname");
audio.play();
}

Then I can define the variable and later use audio.pause() to pause the track. The problem is that I want to do this within javascript because I have a lot of tracks and I don’t want to create audio elements for each one.

Why doesn’t the first piece of code allow me to pause the audio later? Is there any way I can let it pause the audio later? If not, are there any alternatives that involve playing the audio from javascript by passing a parameter which is the song title? I don’t want to have to include the src in the html.

I suspect that jQuery might have an easy solution for this but form what I’ve researched I couldn’t find anything.

Answer by Starx

I just tested a snippet and it works as such

function music(song) {

    var audio = new Audio("audio/" + song + ".ogg");
    audio.play();
    setTimeout(function() { audio.pause(); }, 5000);

}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!