UNPKG

2.22 kBJavaScriptView Raw
1import { optionsFromArguments } from "../core/util/Defaults.js";
2import { WaveShaper } from "../signal/WaveShaper.js";
3import { Effect } from "./Effect.js";
4/**
5 * A simple distortion effect using Tone.WaveShaper.
6 * Algorithm from [this stackoverflow answer](http://stackoverflow.com/a/22313408).
7 * Read more about distortion on [Wikipedia] (https://en.wikipedia.org/wiki/Distortion_(music)).
8 * @example
9 * const dist = new Tone.Distortion(0.8).toDestination();
10 * const fm = new Tone.FMSynth().connect(dist);
11 * fm.triggerAttackRelease("A1", "8n");
12 * @category Effect
13 */
14export class Distortion extends Effect {
15 constructor() {
16 const options = optionsFromArguments(Distortion.getDefaults(), arguments, ["distortion"]);
17 super(options);
18 this.name = "Distortion";
19 this._shaper = new WaveShaper({
20 context: this.context,
21 length: 4096,
22 });
23 this._distortion = options.distortion;
24 this.connectEffect(this._shaper);
25 this.distortion = options.distortion;
26 this.oversample = options.oversample;
27 }
28 static getDefaults() {
29 return Object.assign(Effect.getDefaults(), {
30 distortion: 0.4,
31 oversample: "none",
32 });
33 }
34 /**
35 * The amount of distortion. Nominal range is between 0 and 1.
36 */
37 get distortion() {
38 return this._distortion;
39 }
40 set distortion(amount) {
41 this._distortion = amount;
42 const k = amount * 100;
43 const deg = Math.PI / 180;
44 this._shaper.setMap((x) => {
45 if (Math.abs(x) < 0.001) {
46 // should output 0 when input is 0
47 return 0;
48 }
49 else {
50 return ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x));
51 }
52 });
53 }
54 /**
55 * The oversampling of the effect. Can either be "none", "2x" or "4x".
56 */
57 get oversample() {
58 return this._shaper.oversample;
59 }
60 set oversample(oversampling) {
61 this._shaper.oversample = oversampling;
62 }
63 dispose() {
64 super.dispose();
65 this._shaper.dispose();
66 return this;
67 }
68}
69//# sourceMappingURL=Distortion.js.map
\No newline at end of file