Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 11, 2022 02:09 am GMT

P5 JS Audiovisualizer

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()   }}

Original Link: https://dev.to/stuxnat/p5-js-audiovisualizer-4a32

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To