using slider and cents from library

master
Matthew Huntington 11 months ago
parent b48b5a24de
commit 755354ce7f

@ -1,21 +1,20 @@
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) => {
const flatSharpChar = (centDifference > 0) ? '♯' : '♭'
return flatSharpChar + Math.abs(parseInt(centDifference)).toString().padStart(2, '0')
}
const centsArray = []
const getMedianCents = (cents) => {
centsArray.push(cents)
if(centsArray.length > 50){
centsArray.shift()
}
return centsArray[Math.floor(centsArray.length/2)]
}
function startListening() {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
@ -36,8 +35,13 @@ function startListening() {
analyser.getFloatTimeDomainData(buffer);
const pitch = autoCorrelate(buffer, audioContext.sampleRate);
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))
const heardTone = teoria.note.fromFrequency(pitch)
const generatedTone = teoria.note.fromFrequency(newTone)
if(heardTone.note.toString() === generatedTone.note.toString()){
const medianCents = Math.floor(getMedianCents(heardTone.cents-generatedTone.cents))
document.querySelector('#analyze-pitch input[type="range"]').value = medianCents
document.querySelector('#analyze-pitch label').innerText = medianCents
}
}
};
})

@ -12,6 +12,13 @@
font-family: monospace;
line-height:2em;
}
label {
display:block;
}
input[type="range"] {
-webkit-appearance: none;
border: 1px solid black;
}
</style>
</head>
<body>
@ -33,12 +40,8 @@
<section id="analyze-pitch">
<h2>Pitch Analyzer</h2>
<button>Analyze</button>
<dl>
<dt>Pitch:</dt>
<dd></dd>
<dt>Cents flat/sharp</dt>
<dd></dd>
</dl>
<label></label>
<input type="range" min="-50" max="50" value="0"/>
</section>
</body>
</html>

Loading…
Cancel
Save