简体   繁体   English

如何准确同步 <audio> 从Web音频时间轴开始播放

[英]How to accurately sync <audio> playback with start of Web Audio timeline

I'm trying to make it so when the user clicks a button, an audio file is played (via <audio> ), but it fades in using Web Audio's linearRampToValueAtTime method. 我试图这样做,以便当用户单击按钮时,播放音频文件(通过<audio> ),但是使用Web Audio的linearRampToValueAtTime方法淡入。

The whole process starts off by setting gain values on the context timeline: 整个过程从在上下文时间轴上设置增益值开始:

if (fadeIn) {
  console.log('0 gain at', currentTime);
  console.log('fade to 1 by', currentTime + fadeIn);
  this.trackGain.gain.setValueAtTime(0, currentTime);
  this.trackGain.gain.linearRampToValueAtTime(1, currentTime + fadeIn);
} else {
  this.trackGain.gain.setValueAtTime(1, currentTime);
}

And then after that's done: 然后完成:

await this.$refs.audio.play();
await this.audioCtx.resume();
// currentTime must be set after play starts, for Safari
this.$refs.audio.currentTime = this.trackList[0].startTime;

When I trigger this process in Chrome, the numbers look good: 当我在Chrome中触发此过程时,数字看起来不错:

在此处输入图片说明

They're not perfect (with track gain starting at 0), but it's close enough. 它们并不完美(轨道增益从0开始),但是足够接近。 In Safari, however, this delay before the audio starts playing is much worse. 但是,在Safari中,音频开始播放之前的这种延迟要严重得多。 The context timeline has enough time to start ramping up before the audio element plays. 上下文时间线有足够的时间开始播放音频元素之前的时间。

在此处输入图片说明

As you can see, the context timeline runs for a while, and track gain starts at 0.31 instead of 0. 如您所见,上下文时间轴运行了一段时间,并且跟踪增益从0.31开始而不是0。

Here's the full code: https://codesandbox.io/s/ykjkoj3yvv 这是完整的代码: https : //codesandbox.io/s/ykjkoj3yvv

Am I maybe doing something wrong here? 我可能在这里做错了吗? Am I doing things out of order? 我是在做乱序的事情吗? How should I address this? 我该如何解决?

Side note: in Firefox, trackGain.gain.value is always 1 no matter what. 旁注:在Firefox中, trackGain.gain.valuetrackGain.gain.value始终为1。 Seems like a bug. 好像是个错误。

My guess is that somehow Safari is getting to the "this.trackGain.gain.setValueAtTime(0, currentTime)" BEFORE updating currentTime after the await() sections - because there's a discontinuous jump that is consistent with a setLinearRampAtTime() call being fired with a time value that is in the past. 我的猜测是Safari在await()节之后更新currentTime之前,以某种方式Safari到达了“ this.trackGain.gain.setValueAtTime(0,currentTime)”-因为存在一个不连续的跳转,该跳转与被触发的setLinearRampAtTime()调用一致具有过去的时间值。 The setValue/setLinear calls look like they're firing between t=0.60 and t=0.62 (try adding a console.log to the set section to test). setValue / setLinear调用看起来好像在t = 0.60和t = 0.62之间触发(尝试将console.log添加到set部分进行测试)。

That would be consistent with the math - the values are roughly consistent with a ramp that has its initial point set to 0 at t=0, and a ramp set to value=1 at t=2. 这将与数学相符-值与在t = 0时将其初始点设置为0且在t = 2时将其设置为value = 1的斜坡大致一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM