I have a function tied to an onClick event. It's supposed to play a song. If there's a song already playing it's supposed to stop the current song and start playing the new one. The only problem is that as far as I know there is only a pause method and it means that the previous song will resume from the paused position and not the beginning. Is there any way around this (like a .stop() method)?
Here's my code:
var currSong="";
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
document.getElementById(newSong).play();
currSong = newSong;
}
}
The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method.
The play() method starts playing the current audio. Tip: This method is often used together with the pause() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).
From looking at the MDC documentation for the audio
element, it appears that the correct way to do this is by setting the currentTime
property:
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
var newSongEl = document.getElementById(newSong);
newSongEl.currentTime = 0;
newSongEl.play();
currSong = newSong;
}
}
Also, it would be better to store the relevant element in currSong
, rather than its ID, unless you are using the ID for something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With