show cents sharp/flat

master
Matthew Huntington 1 year ago
parent bf41389360
commit 33a1d49c57

@ -1,5 +1,22 @@
document.querySelector('#analyze-pitch button').addEventListener('click', startListening); 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() { function startListening() {
navigator.mediaDevices.getUserMedia({ audio: true, video: false }) navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => { .then(stream => {
@ -19,7 +36,10 @@ function startListening() {
const buffer = new Float32Array(analyser.fftSize); const buffer = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(buffer); analyser.getFloatTimeDomainData(buffer);
const pitch = autoCorrelate(buffer, audioContext.sampleRate); 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 => { .catch(err => {

@ -7,6 +7,12 @@
<script src="teoria.js"></script> <script src="teoria.js"></script>
<script src="app.js" defer></script> <script src="app.js" defer></script>
<script src="analyze.js" defer></script> <script src="analyze.js" defer></script>
<style>
body {
font-family: monospace;
line-height:2em;
}
</style>
</head> </head>
<body> <body>
<h1>Tuner</h1> <h1>Tuner</h1>
@ -28,6 +34,8 @@
<dl> <dl>
<dt>Pitch:</dt> <dt>Pitch:</dt>
<dd></dd> <dd></dd>
<dt>Cents flat/sharp</dt>
<dd></dd>
</dl> </dl>
</section> </section>
</body> </body>

Loading…
Cancel
Save