Creating an application that captures audio from a microphone, analyzes the frequencies of the user's singing, and visually displays this information involves several components:
- Audio Capture: Accessing the user's microphone using the Web Audio API.
- Frequency Analysis: Using FFT (Fast Fourier Transform) to analyze the frequency spectrum of the captured audio.
- Frequency Range Determination: Mapping the detected frequencies to musical notes within a suitable range.
- User Interface: Designing an interface to display real-time frequency data and visual performance feedback.
Below is a comprehensive solution using HTML, CSS, and JavaScript. This solution leverages the Web Audio API for audio processing and the HTML5 <canvas> element for visual representation.
1. Setting Up the HTML Structure
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Real-Time Singing Analyzer</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #121212;
color: #ffffff;
}
#controls {
margin: 20px;
}
#frequencyCanvas, #noteCanvas {
border: 1px solid #444;
background-color: #1e1e1e;
border-radius: 8px;
}
#currentNote {
font-size: 2em;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Real-Time Singing Analyzer</h1>
<div id="controls">
<button id="startButton">Start Analysis</button>
<button id="stopButton" disabled>Stop Analysis</button>
</div>
<div>
<canvas id="frequencyCanvas" width="800" height="300"></canvas>
</div>
<div>
<canvas id="noteCanvas" width="800" height="100"></canvas>
</div>
<div id="currentNote">Current Note: --</div>
<script src="app.js"></script>
</body>
</html>
2. Styling with CSS
The <style> section within the HTML handles basic styling to ensure the application looks modern and clean. You can customize these styles or move them to a separate CSS file (styles.css) if preferred.
3. Implementing the JavaScript Logic
Create an app.js file with the following content:
// Check for Web Audio API support
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
alert('Web Audio API is not supported in this browser.');
}
// Select DOM elements
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const frequencyCanvas = document.getElementById('frequencyCanvas');
const noteCanvas = document.getElementById('noteCanvas');
const currentNoteDisplay = document.getElementById('currentNote');
const freqCtx = frequencyCanvas.getContext('2d');
const noteCtx = noteCanvas.getContext('2d');
let audioContext;
let analyser;
let microphone;
let animationId;
// Define musical notes and their frequencies (A4 = 440 Hz)
const noteFrequencies = [
{ note: 'C4', freq: 261.63 },
{ note: 'C#4', freq: 277.18 },
{ note: 'D4', freq: 293.66 },
{ note: 'D#4', freq: 311.13 },
{ note: 'E4', freq: 329.63 },
{ note: 'F4', freq: 349.23 },
{ note: 'F#4', freq: 369.99 },
{ note: 'G4', freq: 392.00 },
{ note: 'G#4', freq: 415.30 },
{ note: 'A4', freq: 440.00 },
{ note: 'A#4', freq: 466.16 },
{ note: 'B4', freq: 493.88 },
{ note: 'C5', freq: 523.25 },
// Add more notes as needed
];
// Function to map frequency to the nearest musical note
function getClosestNote(freq) {
let minDiff = Infinity;
let closestNote = null;
for (let i = 0; i < noteFrequencies.length; i++) {
const diff = Math.abs(freq - noteFrequencies[i].freq);
if (diff < minDiff) {
minDiff = diff;
closestNote = noteFrequencies[i].note;
}
}
return closestNote;
}
// Function to start audio processing
async function startAnalysis() {
// Initialize Audio Context
audioContext = new (window.AudioContext || window.webkitAudioContext)();
try {
// Request microphone access
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
microphone = audioContext.createMediaStreamSource(stream);
// Create Analyser Node
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
microphone.connect(analyser);
// Start visualization
drawFrequency();
startButton.disabled = true;
stopButton.disabled = false;
} catch (err) {
alert('Microphone access denied or not available.');
console.error(err);
}
}
// Function to stop audio processing
function stopAnalysis() {
if (microphone) {
microphone.disconnect();
}
if (analyser) {
analyser.disconnect();
}
if (audioContext) {
audioContext.close();
}
cancelAnimationFrame(animationId);
freqCtx.clearRect(0, 0, frequencyCanvas.width, frequencyCanvas.height);
noteCtx.clearRect(0, 0, noteCanvas.width, noteCanvas.height);
currentNoteDisplay.textContent = 'Current Note: --';
startButton.disabled = false;
stopButton.disabled = true;
}
// Function to draw frequency spectrum and detect note
function drawFrequency() {
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
freqCtx.clearRect(0, 0, frequencyCanvas.width, frequencyCanvas.height);
noteCtx.clearRect(0, 0, noteCanvas.width, noteCanvas.height);
function draw() {
animationId = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
// Draw frequency bars
freqCtx.fillStyle = '#1e1e1e';
freqCtx.fillRect(0, 0, frequencyCanvas.width, frequencyCanvas.height);
const barWidth = (frequencyCanvas.width / bufferLength) * 2.5;
let barHeight;
let x = 0;
for(let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
freqCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
freqCtx.fillRect(x, frequencyCanvas.height - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
// Frequency Analysis for Pitch Detection
const freq = getDominantFrequency(dataArray, audioContext.sampleRate, analyser.fftSize);
if (freq) {
const closestNote = getClosestNote(freq);
currentNoteDisplay.textContent = `Current Note: ${closestNote} (${freq.toFixed(2)} Hz)`;
// Visual representation of the note
noteCtx.clearRect(0, 0, noteCanvas.width, noteCanvas.height);
noteCtx.fillStyle = '#1e1e1e';
noteCtx.fillRect(0, 0, noteCanvas.width, noteCanvas.height);
noteCtx.font = '48px Arial';
noteCtx.fillStyle = '#00ff00';
noteCtx.textAlign = 'center';
noteCtx.fillText(closestNote, noteCanvas.width / 2, noteCanvas.height / 1.5);
}
}
draw();
}
// Function to find the dominant frequency using autocorrelation
function getDominantFrequency(dataArray, sampleRate, fftSize) {
// Find the peak in the frequency data
let maxVal = -Infinity;
let maxIndex = -1;
for (let i = 0; i < dataArray.length; i++) {
if (dataArray[i] > maxVal) {
maxVal = dataArray[i];
maxIndex = i;
}
}
// Convert index to frequency
const freq = maxIndex * sampleRate / fftSize;
// Consider human singing range roughly between 80 Hz to 1000 Hz
if (freq < 80 || freq > 1000) {
return null;
}
return freq;
}
// Event listeners for buttons
startButton.addEventListener('click', startAnalysis);
stopButton.addEventListener('click', stopAnalysis);
4. Explanation of the JavaScript Code
-
Checking for Web Audio API Support: Ensures the browser supports required APIs.
-
Selecting DOM Elements: Grabs references to HTML elements like buttons, canvases, and the display area for the current note.
-
Defining Musical Notes: An array noteFrequencies maps musical notes to their corresponding frequencies. You can extend this array to include more octaves as needed.
-
Mapping Frequency to Nearest Note: The getClosestNote function finds the closest musical note to a given frequency by calculating the smallest difference.
-
Starting Audio Processing (startAnalysis):
- Initializes the audio context.
- Requests access to the user's microphone.
- Creates an
AnalyserNode configured for FFT.
- Connects the microphone to the analyser.
- Starts the visualization loop.
-
Stopping Audio Processing (stopAnalysis):
- Disconnects and stops all audio nodes.
- Cancels the animation frame to stop visual updates.
- Clears the canvases and resets the display.
-
Drawing Frequency Spectrum (drawFrequency):
- Uses
requestAnimationFrame for smooth, real-time updates.
- Retrieves frequency data from the analyser.
- Draws frequency bars representing the amplitude of each frequency bin.
- Performs pitch detection by finding the dominant frequency within a humanoid singing range.
- Maps the detected frequency to the nearest musical note.
- Updates the UI to display the current note and its frequency.
-
Dominant Frequency Detection (getDominantFrequency):
- Identifies the highest amplitude frequency bin in the FFT data.
- Converts the bin index to an actual frequency.
- Checks if the frequency falls within the typical singing range (80 Hz to 1000 Hz). Adjust this range based on your target user base.
-
Event Listeners: Bind the startAnalysis and stopAnalysis functions to the corresponding buttons.
5. Enhancements and Considerations
-
Accuracy of Pitch Detection: The current implementation uses a simple peak detection method which might not be highly accurate for all voices and audio qualities. For improved pitch detection, consider implementing more sophisticated algorithms like autocorrelation or using third-party libraries such as Pitch.js.
-
Visual Feedback: Enhance the visual feedback by adding more graphics, responsiveness, or color changes based on performance quality.
-
Responsive Design: Adapt the canvas sizes and layout to be responsive for different screen sizes and devices.
-
Error Handling: Improve error messages and handling mechanisms to provide better user feedback in case of issues.
-
Additional Features: Incorporate features like recording, playback, performance scoring, or comparison with reference pitches.
6. Running the Application
-
File Structure:
index.html
app.js
- (Optional)
styles.css if you separate CSS.
-
Serve the Files: Since accessing microphones often requires serving files over HTTP or HTTPS, it's recommended to use a local server.
-
Allow Microphone Access: When prompted, allow the browser to access your microphone.
-
Start Singing: Click the "Start Analysis" button and begin singing. The application will display the frequency spectrum and identify the closest musical note in real-time.
7. Conclusion
This solution provides a foundational application for real-time singing analysis with frequency visualization and note detection. Depending on your specific needs, you can expand upon this foundation by integrating more advanced audio processing techniques, enhancing the user interface, and adding additional features to provide a richer user experience.