Skip to content

Commit 22cecdc

Browse files
committed
feat: adding ability to get the frequency at the FFT index
`getFrequencyOfIndex`
1 parent d72580c commit 22cecdc

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

Tone/component/analysis/FFT.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ describe("FFT", () => {
3535
fft.dispose();
3636
});
3737

38+
it("can get the frequency values of each index of the return array", () => {
39+
const fft = new FFT(32);
40+
expect(fft.getFrequencyOfIndex(0)).to.be.closeTo(0, 1);
41+
expect(fft.getFrequencyOfIndex(16)).to.be.closeTo(fft.context.sampleRate / 4, 1);
42+
fft.dispose();
43+
});
44+
3845
it("can run waveform analysis", (done) => {
3946
const noise = new Noise();
4047
const fft = new FFT(256);

Tone/component/analysis/FFT.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { ToneAudioNode } from "../../core/context/ToneAudioNode";
22
import { dbToGain } from "../../core/type/Conversions";
3-
import { NormalRange, PowerOfTwo } from "../../core/type/Units";
3+
import { Hertz, NormalRange, PowerOfTwo } from "../../core/type/Units";
44
import { optionsFromArguments } from "../../core/util/Defaults";
55
import { MeterBase, MeterBaseOptions } from "./MeterBase";
6+
import { assert } from "../../core/util/Debug";
67

78
export interface FFTOptions extends MeterBaseOptions {
89
size: PowerOfTwo;
@@ -77,4 +78,15 @@ export class FFT extends MeterBase<FFTOptions> {
7778
set smoothing(val) {
7879
this._analyser.smoothing = val;
7980
}
81+
82+
/**
83+
* Returns the frequency value in hertz of each of the indices of the FFT's [[getValue]] response.
84+
* @example
85+
* const fft = new Tone.FFT(32);
86+
* console.log(fft.getIndexFrequency());
87+
*/
88+
getFrequencyOfIndex(index: number): Hertz {
89+
assert(0 <= index && index < this.size, `index must be greater than or equal to 0 and less than ${this.size}`);
90+
return index * this.context.sampleRate / (this.size * 2);
91+
}
8092
}

0 commit comments

Comments
 (0)