Panini Raman
Panini Raman

Reputation: 501

Javascript method pause() only works with audio element

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.

Upvotes: 0

Views: 2431

Answers (3)

Ali Ahmadi
Ali Ahmadi

Reputation: 133

You can create the audio variable before defining the function.

var audio = new Audio();
function playMusic(song) {
  audio.src = "audio/" + song + ".ogg";
  audio.play();
}
function pauseMusic() {
  audio.pause();
}

Upvotes: 0

Starx
Starx

Reputation: 78971

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

}

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

audio only exists inside the function. if you need access to it outside the function then return the instance of the Audio object you are creating:

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

  return audio;
}

var theTrack = getAudio('my_song', true);
theTrack.pause(); // pause the song
theTrack.play();  // play the song

The second example refers to what i assume is an audio element which in turn exposes the functionality of the Audio object. The reason the second function works anywhere is because the DOM element is always present in the DOM and you are referencing that to get at the underlying Audio API, as opposed to a using the Audio object/API directly.

Upvotes: 1

Related Questions