rserota / wad

Web Audio DAW. Use the Web Audio API for dynamic sound synthesis. It's like jQuery for your ears.
MIT License
1.88k stars 160 forks source link

How do I get the playhead position of a Wad object? #140

Closed W-KE closed 2 years ago

W-KE commented 2 years ago

I'm trying to make a simple music player with Wad, and here is how I used Wad:

const audio = new Wad({ source: 'noise' });
console.log(this.audio.duration); // I can get the length of the audio
audio.play();
// is there a way I can get the current playhead position so I can make a progress bar?
rserota commented 2 years ago

There isn't a single property that provides this information currently, but you can compute the current position like this:

const audioClip = new Wad({source: '/audio/song.wav'})
audioClip.play()

let playheadPosition = Wad.audioContext.currentTime - audioClip.lastPlayedTime

I hope that helps. Cheers!

W-KE commented 2 years ago

Kind of, this only works when you have a fixed playback rate, the position in samples will mismatch with the position in seconds calculated this way when playback with a variable rate. For example, the audio is played with the rate of 1 for 1 second, then sample position is at 44100, and then played with the rate of 2 for 1 second, now the sample position is 3 * 44100, but the position in second calculated with Wad.audioContext.currentTime - audioClip.lastPlayedTime is still 2 seconds, which does not make sense anymore, and can not tell very much information about how many percentage of the audio clip was played.

rserota commented 2 years ago

Yeah, my solution won't work if you need to adjust the playback rate dynamically, but it's the best solution I can offer you. This is a known issue in the Web Audio API. There's a proposal to add a position attribute to the AudioBufferSourceNode, but it hasn't been implemented yet. https://github.com/WebAudio/web-audio-api/issues/2397