Files
esp32i2s/data/index.html
Jose 4992b75d57 feat : Improved visualization by adding logarithmic scaling to the x-axis labels and updating the y-axis scale based on the maximum value of the frequency spectrum.
- Updated the `y-axis scale` based on the maximum value of the frequency spectrum, added logarithmic scaling to the x-axis labels, and improved interpolation logic for better display.
2025-04-25 21:29:16 +02:00

260 lines
10 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>ESP32 Piano Spectrum Analyzer</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background: #f0f0f0;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
text-align: center;
}
#spectrum-container {
position: relative;
height: 400px;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>Piano Spectrum Analyzer</h1>
<div id="spectrum-container">
<canvas id="spectrumChart"></canvas>
</div>
</div>
<script>
Chart.register('chartjs-plugin-annotation');
// Piano note frequencies (Hz)
const noteFrequencies = {
'C2': 65.41, 'C#2': 69.30, 'D2': 73.42, 'D#2': 77.78, 'E2': 82.41, 'F2': 87.31,
'F#2': 92.50, 'G2': 98.00, 'G#2': 103.83, 'A2': 110.00, 'A#2': 116.54, 'B2': 123.47,
'C3': 130.81, 'C#3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'E3': 164.81, 'F3': 174.61,
'F#3': 185.00, 'G3': 196.00, 'G#3': 207.65, 'A3': 220.00, 'A#3': 233.08, 'B3': 246.94,
'C4': 261.63, 'C#4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'E4': 329.63, 'F4': 349.23,
'F#4': 369.99, 'G4': 392.00, 'G#4': 415.30, 'A4': 440.00, 'A#4': 466.16, 'B4': 493.88,
'C5': 523.25, 'C#5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'E5': 659.26, 'F5': 698.46,
'F#5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'A5': 880.00, 'A#5': 932.33, 'B5': 987.77,
'C6': 1046.50
};
// Create ticks for the x-axis
const xAxisTicks = Object.entries(noteFrequencies).filter(([note]) =>
note.length === 2 || note === 'C#4' || note === 'F#4' || note === 'A#4'
).map(([note, freq]) => ({
value: freq,
label: note
}));
// Keep track of recent maximum values
const maxValueHistory = [];
const MAX_HISTORY_LENGTH = 5;
function updateYAxisScale(newValue) {
maxValueHistory.push(newValue);
if (maxValueHistory.length > MAX_HISTORY_LENGTH) {
maxValueHistory.shift();
}
return Math.max(...maxValueHistory) * 1.1; // Add 10% margin
}
const ctx = document.getElementById('spectrumChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
// Generate logarithmically spaced frequencies for labels
labels: Array.from({length: 134}, (_, i) => {
const minFreq = 60;
const maxFreq = 1100;
return Math.pow(10, Math.log10(minFreq) + (Math.log10(maxFreq) - Math.log10(minFreq)) * i / 133);
}),
datasets: [{
label: 'Frequency Spectrum',
data: Array(134).fill(0),
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
fill: true,
backgroundColor: 'rgba(75, 192, 192, 0.2)',
pointRadius: 0 // Hide points for better performance
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 0
},
parsing: {
xAxisKey: 'x',
yAxisKey: 'y'
},
scales: {
y: {
beginAtZero: true,
max: 5000,
adapters: {
update: function(maxValue) {
return updateYAxisScale(maxValue);
}
},
title: {
display: true,
text: 'Magnitude'
}
},
x: {
type: 'logarithmic',
position: 'bottom',
min: 60,
max: 1100,
title: {
display: true,
text: 'Frequency (Hz)'
},
ticks: {
callback: function(value) {
// Show C notes and F# notes
const entries = Object.entries(noteFrequencies);
const closest = entries.reduce((prev, curr) => {
return Math.abs(curr[1] - value) < Math.abs(prev[1] - value) ? curr : prev;
});
if ((closest[0].includes('C') || closest[0].includes('F#')) &&
Math.abs(closest[1] - value) < 1) {
return closest[0];
}
return '';
},
sampleSize: 20,
autoSkip: false
},
grid: {
color: (ctx) => {
const value = ctx.tick.value;
// Check if this tick corresponds to a C note
if (Object.entries(noteFrequencies)
.some(([note, freq]) =>
note.startsWith('C') && Math.abs(freq - value) < 1)) {
return 'rgba(255, 0, 0, 0.1)';
}
return 'rgba(0, 0, 0, 0.1)';
}
}
}
},
plugins: {
annotation: {
annotations: Object.entries(noteFrequencies)
.filter(([note]) => note.startsWith('C'))
.reduce((acc, [note, freq]) => {
acc[note] = {
type: 'line',
xMin: freq,
xMax: freq,
borderColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1,
label: {
content: note,
enabled: true,
position: 'top'
}
};
return acc;
}, {})
},
tooltip: {
callbacks: {
title: function(context) {
const freq = context[0].parsed.x;
// Find the closest note
const closestNote = Object.entries(noteFrequencies)
.reduce((closest, [note, noteFreq]) => {
return Math.abs(noteFreq - freq) < Math.abs(noteFreq - closest.freq)
? { note, freq: noteFreq }
: closest;
}, { note: '', freq: Infinity });
return `Frequency: ${freq.toFixed(1)} Hz (Near ${closestNote.note})`;
}
}
},
legend: {
display: false
}
}
}
});
const wsUrl = `ws://${window.location.hostname}/ws`;
const ws = new WebSocket(wsUrl);
function interpolateSpectrum(spectrum) {
const result = [];
const minFreq = 60;
const maxFreq = 1100;
const binWidth = 8000 / 1024; // Hz per bin
// Generate logarithmically spaced frequencies
for (let i = 0; i < 134; i++) {
const targetFreq = Math.pow(10, Math.log10(minFreq) + (Math.log10(maxFreq) - Math.log10(minFreq)) * i / 133);
// Find the corresponding linear bin
const bin = Math.floor(targetFreq / binWidth);
if (bin >= 8 && bin < 141) {
// Linear interpolation between bins
const binFraction = (targetFreq / binWidth) - bin;
const value = spectrum[bin - 8] * (1 - binFraction) +
(bin - 7 < spectrum.length ? spectrum[bin - 7] : 0) * binFraction;
result.push({
x: targetFreq,
y: value
});
} else {
result.push({
x: targetFreq,
y: 0
});
}
}
return result;
}
ws.onmessage = function(event) {
const spectrum = JSON.parse(event.data);
const interpolatedData = interpolateSpectrum(spectrum);
// Update y-axis scale based on new maximum value
const maxValue = Math.max(...interpolatedData.map(d => d.y));
chart.options.scales.y.max = updateYAxisScale(maxValue);
// Update chart data
chart.data.datasets[0].data = interpolatedData;
chart.update('none'); // Use 'none' mode for maximum performance
};
ws.onclose = function() {
console.log('WebSocket connection closed');
setTimeout(() => {
window.location.reload();
}, 1000);
};
</script>
</body>
</html>