From 33a1d49c577f9062c1bee6c781467faa2ba3ef72 Mon Sep 17 00:00:00 2001 From: Matthew Huntington Date: Fri, 29 Nov 2024 14:43:32 -0500 Subject: [PATCH] show cents sharp/flat --- analyze.js | 22 +++++++++++++++++++++- index.html | 8 ++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/analyze.js b/analyze.js index 36efa42..cd15fd8 100644 --- a/analyze.js +++ b/analyze.js @@ -1,5 +1,22 @@ document.querySelector('#analyze-pitch button').addEventListener('click', startListening); +const calculateCent = (frequency) => { + return frequency * 2 ** (1/1200) - frequency +} + +const getCentDifference = (startingFrequency, newFrequency) => { + const frequencyDifference = newFrequency - startingFrequency + const cent = calculateCent(startingFrequency) + + return frequencyDifference/cent +} + +const generateCentsString = (centDifference) => { + console.log(centDifference); + const flatSharpChar = (centDifference > 0) ? '♯' : '♭' + return flatSharpChar + Math.abs(parseInt(centDifference)).toString().padStart(2, '0') +} + function startListening() { navigator.mediaDevices.getUserMedia({ audio: true, video: false }) .then(stream => { @@ -19,7 +36,10 @@ function startListening() { const buffer = new Float32Array(analyser.fftSize); analyser.getFloatTimeDomainData(buffer); const pitch = autoCorrelate(buffer, audioContext.sampleRate); - document.querySelector('#analyze-pitch dd').textContent = pitch.toFixed(2); + if(pitch != -1){ + document.querySelector('#analyze-pitch dd:nth-of-type(1)').textContent = pitch.toFixed(2) + document.querySelector('#analyze-pitch dd:nth-of-type(2)').innerHTML = generateCentsString(getCentDifference(newTone, pitch)) + } }; }) .catch(err => { diff --git a/index.html b/index.html index fc13041..419946f 100644 --- a/index.html +++ b/index.html @@ -7,6 +7,12 @@ +

Tuner

@@ -28,6 +34,8 @@
Pitch:
+
Cents flat/sharp
+