I'm working on a project, and I can't seem to pause the audio once it starts playing. This is the code I'm running right now:
// <<backmus start 01>>
var executeBackgroundMusic = function(action)
{
var operator = action.options[0]
var song = music[action.options[1]];
var audio = new Audio(music[action.options[1]]);
if (operator == "start"){
audioPlayer["currentlyPlaying"] = song;
audio.play();
audio.loop=true;
}
else if (operator == "stop") {
audio.pause();
audio.currentTime = 0;
audioPlayer["currentlyPlaying"] = "";
}
}
The <<backmus start 01>>
is how I am calling the function, and the song's ID is 01
. When I execute the code, the song starts playing when it is supposed to. When I prompt <<backmus stop 01>>
, however, the song keeps playing. I know it goes through the code, though, because audioPlayer["currentlyPlaying"]
is set to ""
in the console. The start
operator works properly, so I don't think that part is the issue. Is there another way to stop audio besides audio.pause()
?
executeBackgroundMusic()
creates a new Audio
element every time it is called. So when you call it to stop, it is stopping a new Audio
instance, not the one that is playing.
You will have to rework this stack snippet to fit in with your application, but it shows you an example of fixing it.
// EDIT Need this
let music = ["https://archive.org/download/1998-01-suite-pee/Laplace%27s%20Angel.mp3"]
// EDIT Moved out of function so you use the same Audio for both play and pause
var audio = new Audio(music[0]);
// <<backmus start 01>>
var executeBackgroundMusic = function(action) {
var operator = action.options[0]
var song = music[action.options[1]];
// EDIT Do not create a new Audio each time
// var audio = new Audio(music[action.options[1]]);
if (operator == "start") {
// audioPlayer["currentlyPlaying"] = song;
audio.play();
audio.loop = true;
} else if (operator == "stop") {
audio.pause();
audio.currentTime = 0;
// audioPlayer["currentlyPlaying"] = "";
}
}
<button type="button" onclick='executeBackgroundMusic( {options:["start", 0]} )'>Start</button>
<button type="button" onclick='executeBackgroundMusic( {options:["stop", 0]} )'>Stop</button>