单击按钮时使计时器与音乐一起

时间:2017-11-23 21:15:24

标签: javascript html audio timer

我想在点击此按钮时启动计时器。我发现大量的计时器在页面加载时启动。但是没有一个在单击按钮时启动。另一个复杂因素是它需要在声音开始时同时启动。任何帮助将不胜感激。

 <button class="button1" 
 onclick="document.getElementById('sound1').play()">   
 </button>

1 个答案:

答案 0 :(得分:0)

使用javascript,您可以像这样操纵DOM

&#13;
&#13;
//Pause audio on document load
document.getElementById('sound1').pause();
//Detect button clikc
document.getElementById('play').addEventListener("click", cuntingsec, false); 

//Function to count second 
function cuntingsec()
{
  var seconds = 0;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
      seconds += 1;
      el.innerText = "Audio is played " + seconds + " seconds.";
//Detect audio end
document.getElementById('sound1').addEventListener("ended", function(){
            el.innerText = "Audio is played " + seconds + " seconds. and ended";
      //Clear interval
      clearInterval(cancel);

});
  }

  var cancel = setInterval(incrementSeconds, 1000);
}
&#13;
<audio id="sound1" autostart="0" src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay>
  Votre navigateur ne supporte pas l'élément <code>audio</code>.
</audio>
<div id='seconds-counter'> </div>
 <button class="button1"  id="play"
 onclick="document.getElementById('sound1').play()">   
 Play</button>
&#13;
&#13;
&#13;