【问题标题】:Restrict audio playback to specified range将音频播放限制在指定范围内
【发布时间】:2014-10-23 00:01:55
【问题描述】:

假设我有一个 90 秒长的音频文件。

我希望加载此音频文件供用户播放,但播放时间限制在 10 秒到 40 秒之间。

我想要达到的目标:

  • 音频从 10 秒开始
  • 当音频结束时,它会重置为 10 秒标记
  • 音频在 40 秒结束
  • 范围外的音频无法访问

【问题讨论】:

  • 您可以在将音频文件插入页面之前对其进行编辑吗? javascript 有 .currentTime 方法将其设置为 10s
  • 我认为这不可能。至少会非常困难。只需在上传之前编辑音频。

标签: javascript html html5-audio


【解决方案1】:

有类似的问题

解决方法如下,如果有人试图在外面选择,这会将播放拖到片段的开头,同样在片段的末尾这样做:

<audio controls ontimeupdate="restrictAudio(this)">
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">

</audio>
<script>
  function restrictAudio(event) {
    // Trying to stop the player if it goes above 10 second
    if (event.currentTime < 10 || event.currentTime > 40) {
      event.pause();
      event.currentTime = 10
    }
  }
</script>

【讨论】:

    【解决方案2】:
    var startTime = 10;
    var endTime = 15;
    
    // Get our audio (could also get an audio element from the DOM)
    var audio = new Audio('http://www.tonycuffe.com/mp3/cairnomount.mp3');
    
    // Must start before we can set the time
    audio.play();
    
    // Must make sure audio is ready
    // see: http://stackoverflow.com/a/20240607/1968462
    audio.addEventListener("canplay", function() {
        audio.currentTime = startTime;
    });
    
    // Every 1000ms (1 second), we check if we've exceeded the bounds and if so, we
    // set the time back to the end.
    setInterval(function(){
        if(audio.currentTime > endTime) {
            audio.currentTime = startTime;
        }
        console.log(audio.currentTime);
    }, 1000);
    

    示例:http://jsfiddle.net/bn66s67q/1/

    请注意,这不是一个好方法。用户必须下载整个文件,而不仅仅是截断的部分。您应该强烈考虑截断文件。您甚至可以使用音频编辑库来截断服务器端。

    另请注意,这并不准确。我在上面的示例中添加了当前时间的日志记录(在 JavaScript 控制台中查看)。你会注意到你最多可以休息一秒钟。如果需要精度,可以减少间隔时间。

    以上代码可在最新版本的 Firefox、Chrome 和 IE 中运行(我没有测试任何其他版本)。

    【讨论】:

      【解决方案3】:
      <script>
      var audiofile = document.getElementById("myAudio");
       var currenttime=  audiofile.currentTime;
       currenttime=10;
       if(currenttime>39){currenttime=10;}
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-20
        • 2011-08-25
        相关资源
        最近更新 更多