前端js实现麦克风输入的瀑布频谱图
时间: 2023-06-23 19:09:07 浏览: 159
要实现麦克风输入的瀑布频谱图,需要用到Web Audio API和Canvas API。
首先需要获取用户的麦克风输入,可以使用getUserMedia()方法获取:
```javascript
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
// 获取到麦克风输入流stream
})
.catch(error => {
console.log(error);
});
```
接着,我们需要创建一个AudioContext对象,将麦克风输入流作为源,创建Analyser对象,用于分析音频信号:
```javascript
const audioContext = new AudioContext();
const source = audioContext.createMediaStreamSource(stream);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
source.connect(analyser);
```
然后,我们可以使用Canvas API创建一个画布,用于显示瀑布频谱图:
```javascript
const canvas = document.createElement('canvas');
const canvasCtx = canvas.getContext('2d');
document.body.appendChild(canvas);
```
接下来,我们需要实时获取频域数据,然后将数据绘制到画布上。由于频域数据是一个数组,每个元素表示一个频率的能量值,我们可以使用canvasCtx.fillRect()方法绘制矩形,表示每个频率的能量值。同时,为了实现瀑布效果,我们需要将画布中的所有矩形往上移动一定距离,并在底部绘制新的矩形。
```javascript
function draw() {
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(dataArray);
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
canvasCtx.fillStyle = '#00ff00';
canvasCtx.globalAlpha = 0.5;
const barWidth = canvas.width / dataArray.length;
let x = 0;
for (let i = 0; i < dataArray.length; i++) {
const barHeight = canvas.height * dataArray[i] / 255;
canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
x += barWidth;
}
canvasCtx.drawImage(canvas, 0, -1);
requestAnimationFrame(draw);
}
draw();
```
最后,我们需要调用draw()函数,开始实时绘制瀑布频谱图。完整代码如下:
```javascript
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const audioContext = new AudioContext();
const source = audioContext.createMediaStreamSource(stream);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
source.connect(analyser);
const canvas = document.createElement('canvas');
const canvasCtx = canvas.getContext('2d');
document.body.appendChild(canvas);
function draw() {
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(dataArray);
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
canvasCtx.fillStyle = '#00ff00';
canvasCtx.globalAlpha = 0.5;
const barWidth = canvas.width / dataArray.length;
let x = 0;
for (let i = 0; i < dataArray.length; i++) {
const barHeight = canvas.height * dataArray[i] / 255;
canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
x += barWidth;
}
canvasCtx.drawImage(canvas, 0, -1);
requestAnimationFrame(draw);
}
draw();
})
.catch(error => {
console.log(error);
});
```
阅读全文