How do I get the playhead position of a Wad object?
W-KE opened this issue · 3 comments
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?
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!
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.
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.
WebAudio/web-audio-api#2397