开发者

Starting and Stopping Audio in Javascript

开发者 https://www.devze.com 2023-02-08 22:49 出处:网络
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

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 != "" ) {
                docu开发者_StackOverflow社区ment.getElementById(currSong).pause();
            }           
            document.getElementById(newSong).play();
            currSong = newSong;
        }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消