UNPKG

2.79 kBPlain TextView Raw
1import { Frequency, Positive } from "../core/type/Units.js";
2import { Filter, FilterOptions } from "../component/filter/Filter.js";
3import { SourceOptions } from "../source/Source.js";
4import { optionsFromArguments } from "../core/util/Defaults.js";
5import { LFOEffect, LFOEffectOptions } from "./LFOEffect.js";
6
7export interface AutoFilterOptions extends LFOEffectOptions {
8 baseFrequency: Frequency;
9 octaves: Positive;
10 filter: Omit<
11 FilterOptions,
12 keyof SourceOptions | "frequency" | "detune" | "gain"
13 >;
14}
15
16/**
17 * AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency.
18 * Setting the LFO rate and depth allows for control over the filter modulation rate
19 * and depth.
20 *
21 * @example
22 * // create an autofilter and start it's LFO
23 * const autoFilter = new Tone.AutoFilter("4n").toDestination().start();
24 * // route an oscillator through the filter and start it
25 * const oscillator = new Tone.Oscillator().connect(autoFilter).start();
26 * @category Effect
27 */
28export class AutoFilter extends LFOEffect<AutoFilterOptions> {
29 readonly name: string = "AutoFilter";
30
31 /**
32 * The filter node
33 */
34 readonly filter: Filter;
35
36 /**
37 * The octaves placeholder
38 */
39 private _octaves!: Positive;
40
41 /**
42 * @param frequency The rate of the LFO.
43 * @param baseFrequency The lower value of the LFOs oscillation
44 * @param octaves The number of octaves above the baseFrequency
45 */
46 constructor(
47 frequency?: Frequency,
48 baseFrequency?: Frequency,
49 octaves?: Positive
50 );
51 constructor(options?: Partial<AutoFilterOptions>);
52 constructor() {
53 const options = optionsFromArguments(
54 AutoFilter.getDefaults(),
55 arguments,
56 ["frequency", "baseFrequency", "octaves"]
57 );
58 super(options);
59
60 this.filter = new Filter(
61 Object.assign(options.filter, {
62 context: this.context,
63 })
64 );
65
66 // connections
67 this.connectEffect(this.filter);
68 this._lfo.connect(this.filter.frequency);
69 this.octaves = options.octaves;
70 this.baseFrequency = options.baseFrequency;
71 }
72
73 static getDefaults(): AutoFilterOptions {
74 return Object.assign(LFOEffect.getDefaults(), {
75 baseFrequency: 200,
76 octaves: 2.6,
77 filter: {
78 type: "lowpass" as const,
79 rolloff: -12 as -12,
80 Q: 1,
81 },
82 });
83 }
84
85 /**
86 * The minimum value of the filter's cutoff frequency.
87 */
88 get baseFrequency(): Frequency {
89 return this._lfo.min;
90 }
91 set baseFrequency(freq) {
92 this._lfo.min = this.toFrequency(freq);
93 // and set the max
94 this.octaves = this._octaves;
95 }
96
97 /**
98 * The maximum value of the filter's cutoff frequency.
99 */
100 get octaves(): Positive {
101 return this._octaves;
102 }
103 set octaves(oct) {
104 this._octaves = oct;
105 this._lfo.max = this._lfo.min * Math.pow(2, oct);
106 }
107
108 dispose(): this {
109 super.dispose();
110 this.filter.dispose();
111 return this;
112 }
113}