Skip to content

Commit

Permalink
feat: adding ability to get the frequency at the FFT index
Browse files Browse the repository at this point in the history
`getFrequencyOfIndex`
  • Loading branch information
tambien committed Jun 8, 2020
1 parent d72580c commit 22cecdc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
7 changes: 7 additions & 0 deletions Tone/component/analysis/FFT.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ describe("FFT", () => {
fft.dispose();
});

it("can get the frequency values of each index of the return array", () => {
const fft = new FFT(32);
expect(fft.getFrequencyOfIndex(0)).to.be.closeTo(0, 1);
expect(fft.getFrequencyOfIndex(16)).to.be.closeTo(fft.context.sampleRate / 4, 1);
fft.dispose();
});

it("can run waveform analysis", (done) => {
const noise = new Noise();
const fft = new FFT(256);
Expand Down
14 changes: 13 additions & 1 deletion Tone/component/analysis/FFT.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ToneAudioNode } from "../../core/context/ToneAudioNode";
import { dbToGain } from "../../core/type/Conversions";
import { NormalRange, PowerOfTwo } from "../../core/type/Units";
import { Hertz, NormalRange, PowerOfTwo } from "../../core/type/Units";
import { optionsFromArguments } from "../../core/util/Defaults";
import { MeterBase, MeterBaseOptions } from "./MeterBase";
import { assert } from "../../core/util/Debug";

export interface FFTOptions extends MeterBaseOptions {
size: PowerOfTwo;
Expand Down Expand Up @@ -77,4 +78,15 @@ export class FFT extends MeterBase<FFTOptions> {
set smoothing(val) {
this._analyser.smoothing = val;
}

/**
* Returns the frequency value in hertz of each of the indices of the FFT's [[getValue]] response.
* @example
* const fft = new Tone.FFT(32);
* console.log(fft.getIndexFrequency());
*/
getFrequencyOfIndex(index: number): Hertz {
assert(0 <= index && index < this.size, `index must be greater than or equal to 0 and less than ${this.size}`);
return index * this.context.sampleRate / (this.size * 2);
}
}

0 comments on commit 22cecdc

Please sign in to comment.