I want to log the volume level of an audio file as its playing, to see if it hits a threshold. I tried using the .createAnalyzer function but can't figure it out. I have the function "repeat" to check every 0.1 seconds for a new volume, I just don't know how to actually get the volume.
const audioContext = new AudioContext();
const audiodiv = document.querySelector('.audiodiv')
const buffer = audioContext.createBuffer(
1,
audioContext.sampleRate * 1,
audioContext.sampleRate
);
const channelData = buffer.getChannelData(0)
for (let i = 0; i < buffer.length; i++){
channelData[i] = Math.random() * 2 - 1;
}
//OUTPUT VOLUME
const primaryGainControl = audioContext.createGain()
primaryGainControl.gain.setValueAtTime(0.01, 0);
primaryGainControl.connect(audioContext.destination);
//SAMPLE
const songbutton = document.createElement('button')
songbutton.innerText = 'song'
songbutton.addEventListener('click', async () => {
const response = await fetch('testsong.wav')
const soundBuffer = await response.arrayBuffer()
const songBuffer = await audioContext.decodeAudioData(soundBuffer)
const songSource = audioContext.createBufferSource()
songSource.buffer = songBuffer
const songSource2 = audioContext.createBufferSource()
songSource2.buffer = songBuffer
songSource.playbackRate.setValueAtTime(1, 0)
songSource2.playbackRate.setValueAtTime(1, 0)
const songGain = audioContext.createGain()
songGain.gain.setValueAtTime(0.01, 0)
const analyserNode = audioContext.createAnalyser();
analyserNode.connect(primaryGainControl)
repeat()
function repeat(){
setTimeout(() => {
console.log(analyzerNode.VOLUME)
repeat()
}, 100);
}
console.log(analyserNode.frequencyBinCount)
songSource.connect(primaryGainControl)
songSource2.connect(analyserNode)
songSource2.start()
console.log(songSource2.amplitude)
})
audiodiv.appendChild(songbutton)