This content originally appeared on DEV Community and was authored by Natalie Taktachev
One of my favorite things about coding is that I can make fun projects with it like building an audiovisualizer. Here is how to do it in p5!
Before beginning, make sure to include the p5 sound library and reference it in your HTML file. Next:
Step 1. Set up your canvas
function setup() {
createCanvas(windowWidth, WindowHeight);
}
function draw(){
background(0);
}
Step 2. Load the music
We will create a global variable for the song, and in this example, it will be a local file. We will also create a function that will play the song only when the mouse is clicked, because some browsers do not support autoplay.
const song
function preload(){
song = loadSoung('example.mp3')
}
function setup() {
createCanvas(windowWidth, WindowHeight);
}
function draw(){
background(0);
}
function mouseClicked(){
if (song.isPlaying()) {
song.pause()
} else {
song.play()
}
}
Step 3. Capture the audio and analyze it
In this step, we will use Fast Fourier Transform (FFT). FFT will analyze the sound in every frame of the song and return an array with data about the sound.
const song
const fft
function preload(){
song = loadSoung('example.mp3')
}
function setup() {
createCanvas(windowWidth, WindowHeight);
fft = new p5.FFT()
}
function draw(){
background(0);
}
function mouseClicked(){
if (song.isPlaying()) {
song.pause()
} else {
song.play()
}
}
Step 4. Visualize the data
In this step, we will use Fast Fourier Transform (FFT). FFT will analyze the sound in every frame of the song and return an array with data about the sound. This should give you a waveform across the canvas which you can manipulate however you want (like changing colors, or creating a circle)!
const song
const fft
function preload(){
song = loadSoung('example.mp3')
}
function setup() {
createCanvas(windowWidth, WindowHeight);
fft = new p5.FFT()
}
function draw(){
background(0);
stroke(255);
noFill()
const wave = fft.waveform()
beginShape()
for (let i = 0; i < width; i++{
const index = floor(map(i, 0, width, 0, wave.length))
const x = i
const y = wave[index] * 200 + height / 2
vertex(x, y)
}
endShape()
}
function mouseClicked(){
if (song.isPlaying()) {
song.pause()
} else {
song.play()
}
}
This content originally appeared on DEV Community and was authored by Natalie Taktachev
Natalie Taktachev | Sciencx (2022-04-11T02:09:38+00:00) P5 JS Audiovisualizer. Retrieved from https://www.scien.cx/2022/04/11/p5-js-audiovisualizer/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.