点击播放音频并在点击时重新开始

31

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

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

当我点击 play 按钮时,音频文件开始播放,但是当我再次点击按钮时,音频文件不会停止,并且直到文件结束后才能再次播放。

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

我是否可以使用 onclick 来点击按钮重新启动音频文件,而不必等待歌曲停止?

3个回答

68

要只是重新开始这首歌,您可以执行以下操作:

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

FIDDLE

要切换它,例如在再次单击时停止音频,当再次单击时,它从开头重新开始播放,您需要执行更像是:

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

FIDDLE


(翻译:这是一个包含 FIDDLE 链接的段落。)

但是如果您正在使用多个文件和/或按钮呢? - Rafael

1
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();

当点击事件发生时,启动马的声音并暂停当前正在播放的所有其他声音:

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

});


0
function sound(src) {
    this.sound = document.createElement("audio");
    this.sound.src = src;
    this.sound.setAttribute("preload", "auto");
    this.sound.setAttribute("controls", "none");
    //this.sound.style.display = "none";
    document.body.appendChild(this.sound);
    this.play = function () {
        this.sound.play();
    }
    this.stop = function () {
        this.sound.pause();
        this.sound.currentTime = 0
    }
}

你可以使用 /above 函数来播放声音。
 let mysound1 = new sound('xyz.mp3')
 mysound1.play()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接