const bottomPadding = 20;
const rightPadding = 100;
const waveformHeight = 35;
const displaySampleRate = 100;
sound = loadSound('mp3.mp3');
const buffer = sound.buffer;
numFrames = buffer.length;
const rawSamples = buffer.getChannelData(0);
const displaySampleCount = Math.floor(numFrames / displaySampleRate);
displaySamples = new Array(displaySampleCount);
for (let i = 0; i < displaySampleCount; i++) {
const sampleIndex = i * displaySampleRate;
const sample = rawSamples[sampleIndex];
maxAmp = max(maxAmp, abs(sample));
displaySamples[i] = sample;
for (let i = 0; i < displaySampleCount; i++) {
displaySamples[i] /= maxAmp;
drawWaveform(color(150), leftPadding, width - rightPadding);
let playedWidth = map(sound.currentTime(), 0, sound.duration(), leftPadding, width - rightPadding);
drawWaveform(color(255), leftPadding, playedWidth);
let playheadX = map(sound.currentTime(), 0, sound.duration(), leftPadding, width - rightPadding);
line(playheadX, (height - waveformHeight) / 2, playheadX, (height + waveformHeight) / 2);
const isMouseOverWaveform = (mouseX >= leftPadding && mouseX <= width - rightPadding && mouseY >= (height - waveformHeight) / 2 && mouseY <= (height + waveformHeight) / 2);
if (isMouseOverWaveform) {
line(mouseX, 0, mouseX, height);
textAlign(CENTER, CENTER);
text(formatTime(sound.currentTime()), leftPadding / 2 + 30, height / 2);
text(formatTime(sound.duration() - sound.currentTime()), width - rightPadding / 2, height / 2);
function drawWaveform(col, startX, endX) {
for (let i = 0; i < displaySamples.length; i++) {
const x = map(i, 0, displaySamples.length - 1, leftPadding, width - rightPadding);
const y = map(displaySamples[i], -1, 1, (height + waveformHeight) / 2, (height - waveformHeight) / 2);
if (x >= startX && x <= endX) {
function drawBackgroundBox() {
rect(0, 0, width, height);
function mousePressed() {
if (mouseX >= leftPadding && mouseX <= width - rightPadding && mouseY >= (height - waveformHeight) / 2 && mouseY <= (height + waveformHeight) / 2) {
const clickPosition = constrain(mouseX, leftPadding, width - rightPadding);
const newPosition = map(clickPosition, leftPadding, width - rightPadding, 0, sound.duration());
playhead = clickPosition;
} else if (mouseX >= 10 && mouseX <= 40 && mouseY >= (height / 2 - 15) && mouseY <= (height / 2 + 15)) {
function togglePlayPause() {
rect(10, height / 2 - 15, 30, 30);
rect(15, height / 2 - 10, 5, 20);
rect(25, height / 2 - 10, 5, 20);
vertex(15, height / 2 - 10);
vertex(15, height / 2 + 10);
function formatTime(seconds) {
const minutes = int(seconds / 60);
const secs = int(seconds % 60);
return nf(minutes, 2) + ":" + nf(secs, 2);