Public
Edited
Jan 14, 2023
Insert cell
Insert cell
// Load the audio data
var audio = new Audio("example.mp3");

// Create an SVG element to hold the visualization
var svg = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 300);

// Create a path element to represent the waveform
var path = svg.append("path")
.attr("fill", "none")
.attr("stroke", "black");

// Use the Web Audio API to analyze the audio data
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
var source = audioContext.createMediaElementSource(audio);
var analyser = audioContext.createAnalyser();
source.connect(analyser);
analyser.connect(audioContext.destination);

// Create a buffer to hold the audio data
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);

// Draw the waveform using D3
function draw() {
requestAnimationFrame(draw);

// Copy the audio data into the buffer
analyser.getByteTimeDomainData(dataArray);

// Scale the data to fit within the SVG element
var y = d3.scaleLinear()
.domain([0, 255])
.range([300, 0]);

// Create the D3 line generator
var line = d3.line()
.x(function(d, i) { return i * (800 / bufferLength); })
.y(function(d) { return y(d); });

// Update the path element with the new data
path.datum(dataArray)
.attr("d", line);
}

// Start the visualization
draw();

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