Last active
January 28, 2021 14:07
-
-
Save fffiloni/a22a6047b0b651ca7e438cb1aa97d6b7 to your computer and use it in GitHub Desktop.
Converts audio peaks to bars and renders them on p5js canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let peaks = []; | |
let rectRadius = 4; | |
let barsW = 3; | |
let soundFile = loadSound('path/to/audio.mp3'); // loadSound() is a p5sound method | |
// loadSound inside the preload() function | |
// We calculate audio peaks to show bars and wave | |
// Do this inside setup() function | |
peaks = soundFile.getPeaks(width/(barsW*2)); | |
// width ‹=› Canvas width | |
// getPeaks() is a p5sound method | |
function getAudioBars(){ | |
let barWidth = barsW; | |
let offsetWidth = ((barsW)*2)-1; | |
let offset = 0; | |
let peakValue = 0; | |
for(var i = 0; i < peaks.length; i++){ | |
if(peaks[i] < 0){ | |
peakValue = -peaks[i]; | |
} else { | |
peakValue = peaks[i]; | |
} | |
let barHeight = map(peakValue, 0, 2, 0.1, height-10); | |
push(); | |
noStroke(); | |
let c = color(0, 0, 0); | |
fill(c); | |
rect(i + offset, (height/2) - (barHeight), barWidth, barHeight*2, rectRadius); | |
pop(); | |
offset += offsetWidth; | |
} | |
} | |
// then call getAudioBars() inside p5 draw() function | |
function draw(){ | |
if(soundFile != null){ | |
getAudioBars(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment