在 Javascript 中启动和停止音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4927838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:23:19  来源:igfitidea点击:

Starting and Stopping Audio in Javascript

javascriptaudio

提问by tripleZee

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 pausemethod 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)?

我有一个与 onClick 事件相关的函数。它应该播放一首歌。如果有一首歌曲已经在播放,它应该停止当前歌曲并开始播放新歌曲。唯一的问题是,据我所知只有一个暂停方法,这意味着上一首歌曲将从暂停位置而不是开头继续播放。有没有办法解决这个问题(比如 .stop() 方法)?

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

回答by lonesomeday

From looking at the MDC documentation for the audioelement, it appears that the correct way to do this is by setting the currentTimeproperty:

从查看元素MDC 文档audio来看,正确的方法似乎是通过设置currentTime属性:

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.

此外,最好将相关元素存储在 中currSong,而不是其 ID 中,除非您将 ID 用于其他用途。