Published
Edited
May 19, 2019
1 fork
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
Insert cell
Insert cell
analyser = audioCtx.createAnalyser();
Insert cell
Insert cell
data ={
return navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(function(stream) {
const src = audioCtx.createMediaStreamSource(stream)
src.connect(analyser)
analyser.fftSize = 256
const bufferLength = analyser.fftSize
const dataArray = new Float32Array(bufferLength)
return dataArray
})
}
Insert cell
{
while(true) {
analyser.getFloatFrequencyData(data)
yield data
}
}
Insert cell
Insert cell
Insert cell
{
const canvasCtx = canvas.getContext('2d');
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);

function draw() {
//Schedule next redraw
requestAnimationFrame(draw);

//Draw black background
canvasCtx.fillStyle = 'rgb(110, 110, 110)';
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

//Draw spectrum
const barWidth = (canvas.width / 256) * 2.5;
let posX = 0;
for (let i = 0; i < 256; i++) {
const barHeight = (data[i] + 140) * 2;
canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight + 100) + ', 50, 50)';
canvasCtx.fillRect(posX, canvas.height - barHeight / 2, barWidth, barHeight / 2);
posX += barWidth + 1;
}
};

draw();
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more