【问题标题】:Play audio and restart it onclick播放音频并单击重新启动
【发布时间】:2013-07-14 03:39:54
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript html audio onclick


    【解决方案1】:

    要重新开始播放歌曲,您可以:

    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

    【讨论】:

    • 但是如果您使用多个文件和/或按钮怎么办?
    【解决方案2】:
    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");
    

    });

    【讨论】:

      【解决方案3】:
      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多