[英]Is there any way to track volume with the web audio api
I'd like to be able to track how loud the song gets in realtime, returning a number to represent the current volume of the song.我希望能够实时跟踪歌曲的响度,返回一个数字来表示歌曲的当前音量。 The source is from a sample that plays when you click it.
源来自单击它时播放的示例。 Ive seen tutorials on making a volume meter, but all I want is a number to measure this.
我看过制作音量计的教程,但我想要的只是一个数字来测量它。 here is my starting code.
这是我的起始代码。
const audioContext = new AudioContext();
const samplebutton = document.createElement('button')
samplebutton.innerText = 'sample'
samplebutton.addEventListener('click', async () => {
let volume = 0
const response = await fetch('testsong.wav')
const soundBuffer = await response.arrayBuffer()
const sampleBuffer = await audioContext.decodeAudioData(soundBuffer)
const sampleSource = audioContext.createBufferSource()
sampleSource.buffer = sampleBuffer
sampleSource.connect(audioContext.destination)
sampleSource.start()
function TrackVolume(){
}
You can calculate the volume by passing the audio through an AnalyserNode
.您可以通过
AnalyserNode
传递音频来计算音量。 With it you can get the amplitudes of every frequency at a specific moment in time and calculate the volume of the audio file.有了它,您可以获得特定时刻每个频率的幅度并计算音频文件的音量。
const audioContext = new AudioContext();
const samplebutton = document.createElement('button')
samplebutton.innerText = 'sample'
samplebutton.addEventListener('click', async () => {
const response = await fetch('testsong.wav')
const soundBuffer = await response.arrayBuffer()
const sampleBuffer = await audioContext.decodeAudioData(soundBuffer)
const analyser = audioContext.createAnalyser();
const sampleSource = audioContext.createBufferSource()
sampleSource.buffer = sampleBuffer
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
sampleSource.connect(analyser);
analyser.connect(audioContext.destination)
sampleSource.start()
function caclculateVolume() {
analyser.getByteFrequencyData(dataArray)
let sum = 0;
for (const amplitude of dataArray) {
sum += amplitude * amplitude
}
const volume = Math.sqrt(sum / dataArray.length)
console.log(volume)
requestAnimationFrame(caclculateVolume)
}
caclculateVolume()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.