【发布时间】:2017-03-22 15:47:50
【问题描述】:
当我想知道使用 Web Audio API 播放文件的当前时间时,我遇到了问题。我的代码可以很好地播放文件,当涉及到快速加载的短文件时,getCurrentTime() 函数返回的当前时间足够准确。
但是当我尝试加载大文件时,有时getCurrentTime() 函数返回的当前时间是准确的,有时不是。有时,在等待例如 20 秒以听到文件播放后,当它开始播放时,它说当前时间约为 20 秒(这不是真的,因为它只是在播放文件的开头)。任何音频格式(OGG、MP3、WAV...)都会发生这种情况,但只是有时。
我使用的是慢速系统(Asus EEE PC 901,Intel Atom 1.60 Ghz 和 2 GB RAM,Windows XP Home Edition 和 SP3)和 Firefox 41.0.1。
我不确定,但似乎source.start() 方法开始播放声音的方式为时已晚,所以调用该方法后的行,我为startTime 变量设置值的地方,并不是真正的开始时间。
这里是代码(简化):
var context, buffer, startTime, source;
var stopped = true;
function load(file, startAt)
{
//Here creates the AudioContext and loads the file through XHR (AJAX) and gets the buffer. All works fine.
//When it gots the buffer through XHR (AJAX) and all is fine, it calls play(startAt) function immediately.
//Note: normally, startAt is 0.
}
function play(startAt)
{
source = context.createBufferSource(); //Context created before.
source.buffer = buffer; //Buffer got before from XHR (AJAX).
//Creates a gain node to be able to set the volume later:
var gainNode = context.createGain();
source.connect(gainNode);
gainNode.connect(context.destination);
//Plays the sound:
source.loop = false;
source.start(startAt, 0, buffer.duration - 3); //I don't want the last 3 seconds.
//Stores the start time (useful for pause/resume):
startTime = context.currentTime - startAt; //Here I store the startTime but maybe the file has still not begun to play (should it be just startTime = context.currentTime?).
stopped = false;
}
function stop()
{
source.stop(0);
stopped = true;
}
function getCurrentTime()
{
return (stopped) ? 0 : context.currentTime - startTime;
}
如何检测source.start() 方法何时开始播放文件?所以我可以在那个时候设置startTime 变量值,之前从来没有。
提前非常感谢您。我非常感谢任何形式的帮助。
【问题讨论】:
标签: javascript html web-audio-api