How to make an audio visualizer with HTML CANVAS API ?
Last Updated :
26 Jul, 2024
In this article, we will see how to make an audio visualizer using the canvas API. Canvas API is used to draw graphics on the HTML canvas element. So with this feature, we will make an audio visualizer that responds to the audio from the microphone of the system.
Audio Visualizer can be defined as a tool that visually displays the rhythm, loudness, and frequency of music via animated images.
Classes Used:
- MediaDevices: This is used to access media.
- AudioContext: This is used to create an analyzer.
Methods Used:
- getUserMedia: This gets access to the microphone.
- createMediaStreamSource: This creates a source out of the stream to make an audio visualizer.
- getContext: This method is used to get access to the canvas context.
- requestAnimationFrame: This method helps to create animation.
Approach:
The following steps will follow to create the audio visualizer:
- Create a canvas element to draw the visualizer and button to access the system audio in the HTML code.
- Access your microphone with navigator API, which returns a stream object. MediaDevices is the class that provides access to the audio stream and can be accessed with user events only, so create a button and register a function as shown below.
Syntax:
var btn = document.getElementById("mybtn");
btn.onclick = async()=>{
let stream =await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
});
}
In the above code, we have a button that consists of a callback function for onclick event to access the audio device.
Create an instance of AudioContext class and pass the stream object to it as shown below. Also, create an analyzer that is used to analyze the audio nodes by creating data visualization.
Syntax:
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const mediaStreamSource =
audioContext.createMediaStreamSource(stream);
mediaStreamSource.connect(analyser);
analyser.fftSize = 256;
Define a function drawVisualizer( ) which calls itself continuously at a particular frame rate using the requestAnimationFrame function to reflect the change in the audio signals.
Add the canvas API methods into the drawVisualizer function to create the final visualization, as shown below:
function drawVisualizer() {
requestAnimationFrame(drawVisualizer);
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
const width = visualizer.width;
const height = visualizer.height;
const barWidth = 10;
const canvasContext = visualizer.getContext('2d');
canvasContext.clearRect(0, 0, width, height);
let x = 0;
dataArray.forEach((item, index,array) => {
const y = item / 255 * height*1.1;
canvasContext.strokeStyle = `blue`;
x = x + barWidth;
canvasContext.beginPath();
canvasContext.lineCap = "round";
canvasContext.lineWidth = 2;
canvasContext.moveTo(x, height);
canvasContext.lineTo(x, height - y);
canvasContext.stroke();
})
}
In the above code snippet, initially, we are declaring a typed array to store the audio nodes in terms of integer values ie. dataArray then we are accessing the canvas element created above through JS selector ie.visualizer, and accessing the canvas 2D context ie.canvasContext. We are looping through the elements of the dataArray and for every element, we are drawing a line path from the bottom of the canvas element to the point (x, height - y) from the above code. We have assigned the line color as blue and line width as 2 which helps us in drawing multiple vertical lines.
Example: In this example, we are creating an audio visualizer with canvas API, AudioContext, and mediaDevices.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Creating an audio visualizer
using HTML CANVAS API
</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>
How to make an audio visualizer
with HTML CANVAS API?
</h3>
<button id="mybtn">Click Me</button>
<canvas id="visualizer" width="100px"
height="100px" style="border:5px solid blue;
border-radius:100px">
</canvas>
<script type="text/javascript">
let btn = document.getElementById("mybtn");
let visualizer = document.getElementById("visualizer");
btn.onclick = async () => {
let stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
});
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const mediaStreamSource =
audioContext.createMediaStreamSource(stream);
// Connecting the analyzer to the media source
mediaStreamSource.connect(analyser);
analyser.fftSize = 256;
drawVisualizer();
function drawVisualizer() {
requestAnimationFrame(drawVisualizer)
const bufferLength = analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
// Updating the analyzer with the new
// generated data visualization
analyser.getByteFrequencyData(dataArray)
const width = visualizer.width
const height = visualizer.height
const barWidth = 10
const canvasContext = visualizer.getContext('2d')
canvasContext.clearRect(0, 0, width, height)
let x = 0
dataArray.forEach((item, index, array) => {
// This formula decides the height of the vertical
// lines for every item in dataArray
const y = item / 255 * height * 1.1
canvasContext.strokeStyle = `blue`
// This decides the distances between the
// vertical lines
x = x + barWidth
canvasContext.beginPath();
canvasContext.lineCap = "round";
canvasContext.lineWidth = 2;
canvasContext.moveTo(x, height);
canvasContext.lineTo(x, height - y);
canvasContext.stroke();
})
}
}
</script>
</body>
</html>
Output: This output consists of a circular visualizer which is blue in color and a button beside it to access the system media resources.
Similar Reads
How to sync css animations with HTML5 audio ?
In this article, you will learn to synchronize CSS Animations with audio to create dynamic good websites. This is basically used in online games or animated stories to create some kind of audio effects. We will first analyze the audio and ultimately sync it with the CSS animation property. Approach
8 min read
How to add controls to an audio in HTML5 ?
In this article, we will learn how to add controls to audio in HTML5. The HTML <audio> controls attribute is used to specify the control to play audio which means it allows embedding an HTML5 music player with audio controls straight into the webpage. The current HTML5 most commonly used ogg,
2 min read
How to Change the Size of Audio Player in HTML 5 ?
Customizing the size of an HTML5 audio player allows you to tailor its appearance to fit the style of your website. This is particularly important for websites featuring multimedia content. In this article, we will cover two methods to adjust the size of the HTML5 audio player.Table of Content 1. Us
2 min read
How to Embed Audio and Video in HTML?
HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. It is a combination of Hypertext and Markup language. HTML uses predefined tags and elements that tell the browser how to properly display the content on the screen. So, in this article, we will learn
4 min read
How to draw with mouse in HTML 5 canvas ?
In this article, we shall explore a few ways to draw with the mouse pointer on the HTML 5 canvas. The HTML canvas is essentially a container for various graphics elements such as squares, rectangles, arcs, images, etc. It gives us flexible control over animating the graphics elements inside the canv
4 min read
How to use HTML for Data Visualization ?
In this article, we are going to discuss Data Visualization techniques that can be employed to make the communication of data easier and more effective. Data Visualization in HTML involves presenting data in graphical or visual formats using HTML, CSS, and SVG. It enhances data comprehension and ins
2 min read
How to Play Single Audio Element at a time in HTML ?
To play a single audio element at a time in HTML, use the 'audio' tag and JavaScript. Assign each audio element a unique ID. When playing a new audio, check if any audio is currently playing and pause it before starting the new one. To play a single audio element at a time in HTML using JavaScript,
2 min read
Create a Video and Audio Recorder with JavaScript MediaRecorder API
WebRTC is very popular for accessing device cameras and device microphones and streaming the video or audio media in the browser. But in many cases, we might need to record the streaming for future use or for users (Like user might want to download the streaming, etc.). In that case, we can use the
14 min read
How to mute audio using HTML?
Mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage. Syntax:<audio controls muted>Example: The example shows, mute audio using HTML5, include the 'muted' attribute within the <audio>
1 min read
How to specify the width and height of the canvas using HTML ?
The <canvas> tag in HTML is used to draw graphics on web page using JavaScript. It can be used to draw paths, boxes, texts, gradient, and adding images. By default, it does not contain borders and text. Syntax: <canvas id="canvasID"> HTML Contents... <canvas> Attributes: The canvas
1 min read