尝试使用画布可视化音频文件(.mp3,.wav)的波形时遇到很多麻烦。实际上,对于如何实现这一目标一无所知。
我正在使用Web Audio API。我一直在使用此处的代码来实现我的目标:https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API#Creating_a_waveformoscilloscope。不幸的是,我遇到了问题。下面的例子
波形在画布上的外观:
如果重要的话,这首歌的音频缓冲区大小尤其是8832992。
这首歌的音频缓冲区(songAudioBuffer)如下:
AudioBuffer {
duration: 184.02066666666667,
length: 8832992,
numberOfChannels: 2,
sampleRate: 48000
}
当前程序流程:用户从计算机中选择一个文件->用户单击加载-> FileReader读取音频文件并将其转换为ArrayBuffer->获取ArrayBuffer并创建AudioBuffer
const audioFile = document.querySelector('.audioFile') // Input element where user loads the audio file to
const load = document.querySelector('.load') // button element
load.addEventListener('click', () => {
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(audioFile.files[0]);
fileReader.onload = function(evt){
audioContext = new AudioContext(); // global var
audioBuffer = audioContext.decodeAudioData(fileReader.result); // global var
// Type of AudioBuffer
audioBuffer.then((res) => {
songAudioBuffer = res; // songAudioBuffer is a global var
draw()
})
.catch((err) => {
console.log(err);
})
}
})
function draw(){
const canvas = document.querySelector('.can'); // canvas element
const canvasCtx = canvas.getContext('2d');
canvas.style.width = WIDTH + 'px';
canvas.style.height = HEIGHT + 'px';
canvasCtx.fillStyle = 'rgb(260, 200, 200)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
canvasCtx.beginPath();
const analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
const bufferLength = songAudioBuffer.getChannelData(0).length;
var dataArray = new Float32Array(songAudioBuffer.getChannelData(0));
analyser.getFloatTimeDomainData(songAudioBuffer.getChannelData(0));
var sliceWidth = WIDTH / bufferLength;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
var v = dataArray[i] * 2;
var y = v + (HEIGHT / 4); // Dividing height by 4 places the waveform in the center of the canvas for some reason
if(i === 0) canvasCtx.moveTo(x, y);
else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
}
答案 0 :(得分:0)
只需往后退几步,用-1和1之间的5个值填充一个数组,看看是否可以绘制它。使其更容易发现问题所在。