Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: change post processing example #1465

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions packages/docs/docs/visualize-audio.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,28 +96,40 @@ const params = {
// ---cut---
/**
* This postprocessing step will match the values with what you'd
* get from WebAudio's `AnalyserNode.getByteFrequencyData()`.
* get from WebAudio's `AnalyserNode.getFloatFrequencyData()` and
* `AnalyserNode.getByteFrequencyData()`.
*
* MDN: https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getFloatFrequencyData
* MDN: https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
* W3C Spec: https://www.w3.org/TR/webaudio/#AnalyserNode-methods
*/

// get the frequency data
const frequencyData = visualizeAudio(params);

function toFloatFrequencyData(value: number) {
// convert to decibels (will be in the range `-Infinity` to `0`)
return 20 * Math.log10(value);
}

// default scaling factors from the W3C spec for getByteFrequencyData
const minDb = -100;
const maxDb = -30;

const amplitudes = frequencyData.map((value) => {
// convert to decibels (will be in the range `-Infinity` to `0`)
const db = 20 * Math.log10(value);

function toByteFrequencyData(value: number) {
const db = toFloatFrequencyData(value);

// scale to fit between min and max
const scaled = (db - minDb) / (maxDb - minDb);

const clamped = Math.max(0, Math.min(1, scaled));

// Make it an integer between 0-255
return Math.round(255 * clamped);
}

return scaled;
});
const byteFrequencyData = frequencyData.map(toByteFrequencyData);
const floatFrequencyData = frequencyData.map(toFloatFrequencyData);
```

## See also
Expand Down