使用网络音频在指定持续时间(以毫秒为单位)后停止播放声音 API
Stop playing sound after specified duration in milliseconds using web audio API
在使用 AudioBufferSourceNode 开始播放来自 AudioBuffer 的音频后,如何让它在 毫秒 的预定时间后停止?我的设置很简单:
// create audio source
var source = audioCtx.createBufferSource();
// play audio from source
source.start();
使用 AudioBufferSourceNode.stop() 我只能以秒为单位指定此持续时间,但由于某种原因,提供任何非整数都会评估为零,并使音频立即停止 :
source.stop(0.25); // should be 250 milliseconds, but audio stops immediately
setTimeout 不够精确,偶尔会出现jittering/drifting,尤其是当UI 工作量很大,或者其他地方正在执行其他计算时。
setTimeout(function () {
source.stop(); // very inaccurate
}, 250);
是否有一个简单的解决方案可以在一定的 毫秒 后停止播放音频,而不诉诸于诸如在工作线程中忙等待或类似的 hack?
我认为您误解了 stop()
的第一个参数的作用。
表示相对于音频上下文时间的时间量,也就是说在调用stop()
的时候,需要加上那个时间:
source.stop(context.currentTime + 0.25);
由于函数接受双精度数,因此不应将其四舍五入到最接近的秒数。根据 Web Audio API specification:
The when parameter describes at what time (in seconds) the sound should stop playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will stop playing immediately.
在使用 AudioBufferSourceNode 开始播放来自 AudioBuffer 的音频后,如何让它在 毫秒 的预定时间后停止?我的设置很简单:
// create audio source
var source = audioCtx.createBufferSource();
// play audio from source
source.start();
使用 AudioBufferSourceNode.stop() 我只能以秒为单位指定此持续时间,但由于某种原因,提供任何非整数都会评估为零,并使音频立即停止 :
source.stop(0.25); // should be 250 milliseconds, but audio stops immediately
setTimeout 不够精确,偶尔会出现jittering/drifting,尤其是当UI 工作量很大,或者其他地方正在执行其他计算时。
setTimeout(function () {
source.stop(); // very inaccurate
}, 250);
是否有一个简单的解决方案可以在一定的 毫秒 后停止播放音频,而不诉诸于诸如在工作线程中忙等待或类似的 hack?
我认为您误解了 stop()
的第一个参数的作用。
表示相对于音频上下文时间的时间量,也就是说在调用stop()
的时候,需要加上那个时间:
source.stop(context.currentTime + 0.25);
由于函数接受双精度数,因此不应将其四舍五入到最接近的秒数。根据 Web Audio API specification:
The when parameter describes at what time (in seconds) the sound should stop playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will stop playing immediately.