2015-08-21 64 views
1

我可以以引发“结束”事件的方式手动停止html音频吗?html音频 - 手动停止音频,提高结束事件

<script> 
    var audio = new Audio(); 
    audio.src = "https://translate.google.com/translate_tts?&q=text&tl=en&client=a" 
    audio.play(); 

    audio.addEventListener("ended", function() { 
     console.log("audio ended"); 
    }); 

    audio.addEventListener("play", function() { 
     window.setTimeout(function() { 
      audio.pause(); //stop audio half sec after it starts - this doesn't raise the "ended" event! 
     }, 500); 
    }); 
</script> 
+0

那么你不寻找'结束',你正在寻找'暂停'事件! – blex

+0

为什么你想提高结束的事件?您可以在“播放”侦听器中的setTimeout末尾调用您将从结束事件处理程序调用的代码。 – user2072826

回答

0

你可以这样做,但其对timeupdate事件分别

<audio ontimeupdate="watchTime4Audio(this.currentTime,this.duration)" ... ></audio> 

如下因素代码与jQuery和JS在HTML

//jQuery 
$('audio').on('timeupdate',function(){ 
    if($(this).prop('currentTime')>=$(this).prop('duration')){ 
     //the song has ended you can put your trigger here  
    } 
}); 

//JS 
audio.addEventListener('timeupdate', function() { 
    if(this.currentTime >= this.duration){ 
     //the song has ended you can put your trigger here  
    } 
}); 

使用JavaScript/JQuery的