File size: 9,116 Bytes
f2bee8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import EchoEffect from './effects/echo-effect.js';
import RobotEffect from './effects/robot-effect.js';
import VolumeEffect from './effects/volume-effect.js';
import FadeEffect from './effects/fade-effect.js';
import MuteEffect from './effects/mute-effect.js';
import LowPassEffect from './effects/lowpass-effect.js';
import HighPassEffect from './effects/highpass-effect.js';

const effectTypes = {
    ROBOT: 'robot',
    REVERSE: 'reverse',
    LOUDER: 'higher',
    SOFTER: 'lower',
    FASTER: 'faster',
    SLOWER: 'slower',
    ECHO: 'echo',
    FADEIN: 'fade in',
    FADEOUT: 'fade out',
    MUTE: 'mute',
    LOWPASS: 'low pass',
    HIGHPASS: 'high pass'
};

const centsToFrequency = (cents) => {
    return Math.round(1000000 * Math.pow(2, (cents / 100 / 12))) / 1000000;
}

class AudioEffects {
    static get effectTypes () {
        return effectTypes;
    }
    constructor (buffer, name, trimStart, trimEnd) {
        this.trimStartSeconds = (trimStart * buffer.length) / buffer.sampleRate;
        this.trimEndSeconds = (trimEnd * buffer.length) / buffer.sampleRate;
        this.adjustedTrimStartSeconds = this.trimStartSeconds;
        this.adjustedTrimEndSeconds = this.trimEndSeconds;

        // Some effects will modify the playback rate and/or number of samples.
        // Need to precompute those values to create the offline audio context.
        const pitchRatio = Math.pow(2, 4 / 12); // A major third
        let sampleCount = buffer.length;
        const affectedSampleCount = Math.floor((this.trimEndSeconds - this.trimStartSeconds) *
            buffer.sampleRate);
        let adjustedAffectedSampleCount = affectedSampleCount;
        const unaffectedSampleCount = sampleCount - affectedSampleCount;

        this.playbackRate = 1;
        switch (name) {
            case effectTypes.ECHO:
                sampleCount = Math.max(sampleCount,
                    Math.floor((this.trimEndSeconds + EchoEffect.TAIL_SECONDS) * buffer.sampleRate));
                break;
            case effectTypes.FASTER:
                this.playbackRate = pitchRatio;
                adjustedAffectedSampleCount = Math.floor(affectedSampleCount / this.playbackRate);
                sampleCount = unaffectedSampleCount + adjustedAffectedSampleCount;

                break;
            case effectTypes.SLOWER:
                this.playbackRate = 1 / pitchRatio;
                adjustedAffectedSampleCount = Math.floor(affectedSampleCount / this.playbackRate);
                sampleCount = unaffectedSampleCount + adjustedAffectedSampleCount;
                break;
            default:
                if (!((typeof name === "object") && (name.special === true))) break;
                const options = name;
                if (options.pitch !== null) {
                    this.playbackRate = centsToFrequency(options.pitch);
                    adjustedAffectedSampleCount = Math.floor(affectedSampleCount / this.playbackRate);
                    sampleCount = unaffectedSampleCount + adjustedAffectedSampleCount;
                }
                break;
        }

        const durationSeconds = sampleCount / buffer.sampleRate;
        this.adjustedTrimEndSeconds = this.trimStartSeconds +
            (adjustedAffectedSampleCount / buffer.sampleRate);
        this.adjustedTrimStart = this.adjustedTrimStartSeconds / durationSeconds;
        this.adjustedTrimEnd = this.adjustedTrimEndSeconds / durationSeconds;

        if (window.OfflineAudioContext) {
            this.audioContext = new window.OfflineAudioContext(1, sampleCount, buffer.sampleRate);
        } else {
            // Need to use webkitOfflineAudioContext, which doesn't support all sample rates.
            // Resample by adjusting sample count to make room and set offline context to desired sample rate.
            const sampleScale = 44100 / buffer.sampleRate;
            this.audioContext = new window.webkitOfflineAudioContext(1, sampleScale * sampleCount, 44100);
        }

        // For the reverse effect we need to manually reverse the data into a new audio buffer
        // to prevent overwriting the original, so that the undo stack works correctly.
        // Doing buffer.reverse() would mutate the original data.
        if (name === effectTypes.REVERSE) {
            const originalBufferData = buffer.getChannelData(0);
            const newBuffer = this.audioContext.createBuffer(1, buffer.length, buffer.sampleRate);
            const newBufferData = newBuffer.getChannelData(0);
            const bufferLength = buffer.length;

            const startSamples = Math.floor(this.trimStartSeconds * buffer.sampleRate);
            const endSamples = Math.floor(this.trimEndSeconds * buffer.sampleRate);
            let counter = 0;
            for (let i = 0; i < bufferLength; i++) {
                if (i >= startSamples && i < endSamples) {
                    newBufferData[i] = originalBufferData[endSamples - counter - 1];
                    counter++;
                } else {
                    newBufferData[i] = originalBufferData[i];
                }
            }
            this.buffer = newBuffer;
        } else {
            // All other effects use the original buffer because it is not modified.
            this.buffer = buffer;
        }

        this.source = this.audioContext.createBufferSource();
        this.source.buffer = this.buffer;
        this.name = name;
    }
    process (done) {
        // Some effects need to use more nodes and must expose an input and output
        let input;
        let output;
        switch (this.name) {
            case effectTypes.FASTER:
            case effectTypes.SLOWER:
                this.source.playbackRate.setValueAtTime(this.playbackRate, this.adjustedTrimStartSeconds);
                this.source.playbackRate.setValueAtTime(1.0, this.adjustedTrimEndSeconds);
                break;
            case effectTypes.LOUDER:
                ({input, output} = new VolumeEffect(this.audioContext, 1.25,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.SOFTER:
                ({input, output} = new VolumeEffect(this.audioContext, 0.75,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.ECHO:
                ({input, output} = new EchoEffect(this.audioContext,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.ROBOT:
                ({input, output} = new RobotEffect(this.audioContext,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.LOWPASS:
                ({input, output} = new LowPassEffect(this.audioContext,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.HIGHPASS:
                ({input, output} = new HighPassEffect(this.audioContext,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.FADEIN:
                ({input, output} = new FadeEffect(this.audioContext, true,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.FADEOUT:
                ({input, output} = new FadeEffect(this.audioContext, false,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            case effectTypes.MUTE:
                ({input, output} = new MuteEffect(this.audioContext,
                    this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                break;
            default:
                const name = this.name;
                if (!((typeof name === "object") && (name.special === true))) break;
                const options = name;
                if (options.pitch !== null) {
                    this.source.playbackRate.setValueAtTime(this.playbackRate, this.adjustedTrimStartSeconds);
                    this.source.playbackRate.setValueAtTime(1.0, this.adjustedTrimEndSeconds);
                }
                if (options.volume !== null) {
                    ({input, output} = new VolumeEffect(this.audioContext, options.volume,
                        this.adjustedTrimStartSeconds, this.adjustedTrimEndSeconds));
                }
                break;
        }

        if (input && output) {
            this.source.connect(input);
            output.connect(this.audioContext.destination);
        } else {
            // No effects nodes are needed, wire directly to the output
            this.source.connect(this.audioContext.destination);
        }

        this.source.start();

        this.audioContext.startRendering();
        this.audioContext.oncomplete = ({renderedBuffer}) => {
            done(renderedBuffer, this.adjustedTrimStart, this.adjustedTrimEnd);
        };

    }
}

export default AudioEffects;