Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how I can get current time when use playbackRate.value in Web Audio API

I need to know the current time of a source that is playing, but I can't use context.currentTime because when I change the source.playbackRate.value the speed rate of the context don't change too, so I can't determinate where is the current position of sound. There isn't another way?

Edit, some code:

I use this functions to load and play an mp3 from the network

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
}

Then to get the actual position of the audio track I should do:

var current_position = context.currentTime-inittime;

This work fine while I don't change in the source the playbackRate:

source.playbackRate.value

I need to change this value dynamically to synchronize the audio track to another audio track that is playing, so I need to speed up, if the actual position of the track is lower than the position received from a "server" or slow down if it is higher. But if I change the play back rate how I can know where is currently the position of the audio track?

In fact now if I use

var current_position = context.currentTime-inittime;

current_position will be the time spent from the begin of the playback that is different from the current time position of the playback dude the changes playbackrate value.

like image 790
stefanuc111 Avatar asked Feb 16 '14 20:02

stefanuc111


1 Answers

Use the reciprocal of playbackRate, and multiply the time elapsed since the beginning of playback with that value. Assuming a non-offline rendering, at any given time you can use the following to calculate the actual position that takes playbackRate into consideration:

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

From the documentation of 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.

Which means the value of the value property will take scheduled changes into consideration as well. Note, that the calculated value might go backwards momentarily if playback rate changes quickly.

like image 159
John Weisz Avatar answered Sep 27 '22 21:09

John Weisz