Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting and Stopping Audio in Javascript

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;
        }
}
like image 331
tripleZee Avatar asked Feb 07 '11 23:02

tripleZee


People also ask

How do you stop audio in JavaScript?

The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method.

How do you trigger audio in JavaScript?

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


1 Answers

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.

like image 65
lonesomeday Avatar answered Oct 10 '22 17:10

lonesomeday