Pengubah Warna dengan SUara
Table of Contents
Introduction
This tutorial will guide you through the process of creating a color-changing application that responds to sound. By the end of this guide, you will have a functional project that dynamically alters colors based on audio input, which can be a fun and engaging way to explore sound and visual programming.
Step 1: Set Up Your Development Environment
To start, ensure you have the necessary tools installed on your computer.
- Install a Code Editor: Use an editor like Visual Studio Code or any IDE of your choice.
- Download Required Libraries: You will need libraries such as p5.js for handling audio and visual elements. Install it via:
- Include the following CDN link in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
- Include the following CDN link in your HTML file:
Step 2: Create Your HTML Structure
Set up the basic HTML structure for your application.
- Create a new HTML file (e.g.,
index.html
). - Add the following HTML skeleton:
<!DOCTYPE html> <html> <head> <title>Color Changer with Sound</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script> <script src="sketch.js"></script> <!-- Link to your JavaScript file --> </head> <body> </body> </html>
Step 3: Set Up Your JavaScript File
Create a new JavaScript file (e.g., sketch.js
) where you will write your logic.
- Initialize the sketch with
setup
anddraw
functions:function setup() { createCanvas(windowWidth, windowHeight); // Additional setup code here } function draw() { // Rendering code here }
Step 4: Integrate Audio Input
Incorporate audio input to capture sound levels.
- Use the p5.js
getAudioContext()
to access audio input. - Set up a microphone input:
let mic; function setup() { mic = new p5.AudioIn(); mic.start(); }
Step 5: Change Colors Based on Sound Levels
Now, implement the logic to change colors based on the amplitude of the sound.
- Use the following code to capture the sound amplitude and change the background color:
function draw() { let vol = mic.getLevel(); // Get the current volume level let bgColor = map(vol, 0, 1, 0, 255); // Map volume level to color background(bgColor, 100, 200); // Set the background color }
Step 6: Test Your Application
After implementing the code, it's time to test your application.
- Open your
index.html
file in a web browser. - Allow microphone access when prompted.
- Make sounds and observe how the background color changes in response to the volume.
Conclusion
You have successfully created a color-changing application that reacts to sound. This project introduces basic concepts of audio input and visual programming using p5.js. Explore further by customizing colors, adding shapes, or experimenting with different audio sources. Happy coding!