Html 播放音频并在单击时重新启动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17636310/
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-08-29 11:06:10  来源:igfitidea点击:

Play audio and restart it onclick

javascripthtmlaudioonclick

提问by user2340767

I'm looking to restart an audio file in a HTML5 audio player. I have defined a audio file and a playbutton.

我希望在 HTML5 音频播放器中重新启动音频文件。我已经定义了一个音频文件和一个play按钮。

<audio id="audio1" src="01.wav"></audio>
<button onClick="play()">Play</button>

When I click the playbutton the audio file starts playing, but when I click the button again the audio file doesn't stop and will not play again until it reaches the end of the file.

当我单击该play按钮时,音频文件开始播放,但是当我再次单击该按钮时,音频文件不会停止,并且在到达文件末尾之前不会再次播放。

function play() {
    document.getElementById('audio1').play();
}

Is there a method that would allow me to restart the audio file when I click the button using onclickrather than waiting for the song to stop?

有没有一种方法可以让我在单击按钮时重新启动音频文件onclick而不是等待歌曲停止?

回答by adeneo

To just restart the song, you'd do:

要重新启动歌曲,您可以执行以下操作:

function play() {
    var audio = document.getElementById('audio1');
    if (audio.paused) {
        audio.play();
    }else{
        audio.currentTime = 0
    }
}

FIDDLE

小提琴

To toggle it, as in the audio stops when clicking again, and when click another time it restarts from the beginning, you'd do something more like :

要切换它,就像再次单击时音频停止一样,当再次单击时它会从头开始重新启动,您需要执行以下操作:

function play() {
    var audio = document.getElementById('audio1');
    if (audio.paused) {
        audio.play();
    }else{
        audio.pause();
        audio.currentTime = 0
    }
}

FIDDLE

小提琴

回答by Deepti Gehlot

soundManager.setup({
preferFlash: false,
//, url: "swf/"
onready: function () {
    soundManager.createSound({
        url: [
            "http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3", "http://www.html5rocks.com/en/tutorials/audio/quick/test.ogg"
        ],
        id: "music"
    });
    soundManager.createSound({
        url: [
            "http://www.w3schools.com/html/horse.mp3", 
        ],
        id: "horse"
    });
    soundManager.play("music"); 
}

}).beginDelayedInit();

}).beginDelayedInit();

And to start horse and pause all other sounds currently playing in a click event:

并启动马并暂停当前在点击事件中播放的所有其他声音:

$("#horse").click(function () {
soundManager.stopAll();
soundManager.play("horse");

});

});