diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js')
-rw-r--r-- | testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js b/testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js new file mode 100644 index 0000000000..78f22ccd85 --- /dev/null +++ b/testing/web-platform/tests/html/semantics/embedded-content/media-elements/pitch-detector.js @@ -0,0 +1,58 @@ +// This should be removed when the webaudio/historical.html tests are passing. +// Tracking bug: https://bugs.webkit.org/show_bug.cgi?id=204719 +window.AudioContext = window.AudioContext || window.webkitAudioContext; + +var FFT_SIZE = 2048; + +var audioContext; +var sourceNode; + +function getPitchDetector(media) { + if(!audioContext) { + audioContext = new AudioContext(); + sourceNode = audioContext.createMediaElementSource(media); + } + + var analyser = audioContext.createAnalyser(); + analyser.fftSize = FFT_SIZE; + + sourceNode.connect(analyser); + analyser.connect(audioContext.destination); + + return { + ensureStart() { return audioContext.resume(); }, + detect() { return getPitch(analyser); }, + cleanup() { + sourceNode.disconnect(); + analyser.disconnect(); + }, + }; +} + +function getPitch(analyser) { + // Returns the frequency value for the nth FFT bin. + var binConverter = (bin) => + (audioContext.sampleRate/2)*((bin)/(analyser.frequencyBinCount-1)); + + var buf = new Uint8Array(analyser.frequencyBinCount); + analyser.getByteFrequencyData(buf); + return findDominantFrequency(buf, binConverter); +} + +// Returns the dominant frequency, +/- a certain margin. +function findDominantFrequency(buf, binConverter) { + var max = 0; + var bin = 0; + + for (var i=0;i<buf.length;i++) { + if(buf[i] > max) { + max = buf[i]; + bin = i; + } + } + + // The spread of frequencies within bins is constant and corresponds to + // (1/(FFT_SIZE-1))th of the sample rate. Use the value of bin #1 as a + // shorthand for that value. + return { value:binConverter(bin), margin:binConverter(1) }; +}
\ No newline at end of file |