【问题标题】:How can I hear sound playing while scrubbing the audio from an <audio> tag?从 <audio> 标签中擦洗音频时如何听到声音播放?
【发布时间】:2020-05-22 18:11:33
【问题描述】:

在我的示例中,我有一个用户已上传到网页的 mp3。我在页面上创建了一个可视波形,并让所有默认控件编码并正常工作(播放、暂停、停止、擦洗等...)

我想要实现的是您在 After Effects 或 Animate 中听到的擦洗效果。当我擦洗音频时,我想在擦洗器所在的确切位置听到音频的音调。

我什至不知道从哪里开始?我查看了AudioContext,我认为我的答案在某处,但我不确定。我曾考虑过设置一个“影子音频标签”,将其设置为相同的 src,然后调用 play() 并在不久之后将其暂停,但这似乎是一团糟;尤其是使用强力洗涤器。任何方向将不胜感激!

【问题讨论】:

    标签: html audio web-audio-api audiocontext


    【解决方案1】:

    我认为你在正确的轨道上。您的scrubber UI 可以与未附加到DOM/页面的Audio 元素交互,并且可以直接设置audio.currentTime,播放几毫秒,然后停止。您可以利用取消setTimeout() 队列来创建短暂的清理播放,然后在清理停止时继续播放。我认为这一切都取决于正在下载的完整文件,以避免在清理过程中出现网络延迟。

    【讨论】:

      【解决方案2】:

      是的,您的答案在 AudioContext API 中(所有异步和慢速 MediaElement 都不是为此而设计的)。具体来说,你想要的是AudioBufferSourceNode接口,它可以即时播放音频。

      您需要做的就是将您的音频文件作为 ArrayBuffer 获取,然后从该缓冲区中向 decode the audio PCM data 请求 AudioContext 并从中创建一个 AudioBuffer。

      这是最繁重的部分,但只完成了一次。

      那么你只需要为每个“scrub”事件创建一个非常轻的AudioBufferSourceNode
      为此,您可以使用其start(when, offset, duration) 方法的三参数版本。

      const slider = document.getElementById('slider');
      const ctx = new AudioContext();
      
      fetch("https://upload.wikimedia.org/wikipedia/en/d/dc/Strawberry_Fields_Forever_(Beatles_song_-_sample).ogg")
        .then( resp => resp.arrayBuffer() )
        .then( buf => ctx.decodeAudioData(buf) )
        .then( prepareUI )
        .catch( console.error );
        
      function prepareUI( audioBuf ) {
        let source;
        slider.oninput = e => {
          if( source ) { source.stop(0); }
          source = ctx.createBufferSource();
          source.buffer = audioBuf;
          source.connect(ctx.destination);
          const offset = slider.value * audioBuf.duration;
          const duration = 0.1;
          source.start(0, offset, duration);
        };
        slider.disabled = false;
      }
      input { width: 350px }
      &lt;input type="range" id="slider" min="0" max="1" step="0.005" disabled&gt;

      当然,您也可以为整个播放器重复使用此 AudioBuffer。

      【讨论】:

      • 哇...我永远不会想到这一点。非常感谢!我不得不为我的场景稍微调整它,但它完全可以工作并完成我需要的。 ✋
      猜你喜欢
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多