html - 在 Web Audio API 中使用 playbackRate.value 时如何获取当前时间

标签 html html5-audio web-audio-api

我需要知道正在播放的源的当前时间,但我不能使用 context.currentTime,因为当我更改 source.playbackRate.value 时,上下文的速率也不会改变,所以我无法确定声音的当前位置在哪里。没有别的办法吗?

编辑,一些代码:

我使用这个函数从网络加载和播放 mp3

function loadSoundFile(url) {
    source = null;
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function(e) {
        context.decodeAudioData(request.response, initSound, function() {
            alert("error");
        });
    };
    request.send();
}

var source = null;
var inittime = 0;
function initSound(buffer) 
{

    source = context.createBufferSource();
    source.buffer = buffer;

    source.connect(context.destination);
    source.start(0);
    inittime = context.currentTime; //I save the initial time
}

然后要获取音轨的实际位置,我应该这样做:

var current_position = context.currentTime-inittime;

当我不改变回放率的来源时,这工作正常:

source.playbackRate.value

我需要动态更改此值以使音轨与正在播放的另一个音轨同步,因此我需要加快速度,如果音轨的实际位置低于从“服务器”接收到的位置或速度较慢如果它更高,则向下。但是,如果我改变播放速率,我怎么知道当前音轨的位置在哪里?

事实上如果我现在使用

var current_position = context.currentTime-inittime;

current_position 将是从播放开始花费的时间,与播放的当前时间位置不同,更改 playbackrate 值。

最佳答案

使用 playbackRate 的倒数,并将自开始播放以来耗时乘以该值。假设非离线渲染,在任何给定时间您都可以使用以下方法计算考虑了 playbackRate 的实际位置:

(context.currentTime - inittime) / source.playbackRate.value;

来自 AudioParam.value 的文档:

The value property of the AudioParam interface represents the parameter's current floating point value, which is initially set to the value of AudioParam.defaultValue.

这意味着 value 属性的值也将考虑计划的更改。请注意,如果播放速率变化很快,计算出的值可能会暂时倒退。

关于html - 在 Web Audio API 中使用 playbackRate.value 时如何获取当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816484/

相关文章:

javascript - 在选择下拉菜单中隐藏文件扩展名 (html/css)

html - 用于标题标签下的 anchor 链接的 SEO

javascript - 移动端的 HTML5 可视化

audio - 有人可以告诉我为什么我的白噪声,粉红噪声和棕噪声不起作用(Web Audio API)

JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together

html - 用于 Google Chrome 的类似 Firebug 的调试器

api - 如何使用 Web Audio API 来制作吉他、钢琴等声音

javascript - 循环播放音频次数有限

javascript - Web Audio API - 播放时删除过滤器

android - HTML5 录音在 Google Nexus 中不起作用