crunker 0.4.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/crunker.ts ADDED
@@ -0,0 +1,373 @@
1
+ export interface CrunkerConstructorOptions {
2
+ /**
3
+ * Sample rate for Crunker's internal audio context.
4
+ *
5
+ * @default 44100
6
+ */
7
+ sampleRate: number;
8
+ }
9
+
10
+ export type CrunkerInputTypes = string | File | Blob;
11
+
12
+ /**
13
+ * An exported Crunker audio object.
14
+ */
15
+ export interface ExportedCrunkerAudio {
16
+ blob: Blob;
17
+ url: string;
18
+ element: HTMLAudioElement;
19
+ }
20
+
21
+ /**
22
+ * Crunker is the simple way to merge, concatenate, play, export and download audio files using the Web Audio API.
23
+ */
24
+ export default class Crunker {
25
+ private readonly _sampleRate: number;
26
+ private readonly _context: AudioContext;
27
+
28
+ /**
29
+ * Creates a new instance of Crunker with the provided options.
30
+ */
31
+ constructor({ sampleRate = 44100 }: Partial<CrunkerConstructorOptions> = {}) {
32
+ this._sampleRate = sampleRate;
33
+ this._context = this._createContext();
34
+ }
35
+
36
+ /**
37
+ * Creates Crunker's internal AudioContext.
38
+ *
39
+ * @internal
40
+ */
41
+ private _createContext(): AudioContext {
42
+ window.AudioContext = window.AudioContext || (window as any).webkitAudioContext || (window as any).mozAudioContext;
43
+ return new AudioContext();
44
+ }
45
+
46
+ /**
47
+ * Asynchronously fetches multiple audio files and returns an array of AudioBuffers.
48
+ */
49
+ async fetchAudio(...filepaths: CrunkerInputTypes[]): Promise<AudioBuffer[]> {
50
+ return await Promise.all(
51
+ filepaths.map(async (filepath) => {
52
+ let buffer: ArrayBuffer;
53
+
54
+ if (filepath instanceof File || filepath instanceof Blob) {
55
+ buffer = await filepath.arrayBuffer();
56
+ } else {
57
+ buffer = await fetch(filepath).then((response) => {
58
+ if (response.headers.has('Content-Type') && !response.headers.get('Content-Type')!.includes('audio/')) {
59
+ console.warn(
60
+ `Crunker: Attempted to fetch an audio file, but its MIME type is \`${
61
+ response.headers.get('Content-Type')!.split(';')[0]
62
+ }\`. We'll try and continue anyway. (file: "${filepath}")`
63
+ );
64
+ }
65
+
66
+ return response.arrayBuffer();
67
+ });
68
+ }
69
+
70
+ return await this._context.decodeAudioData(buffer);
71
+ })
72
+ );
73
+ }
74
+
75
+ /**
76
+ * Merges (layers) multiple AudioBuffers into a single AudioBuffer.
77
+ *
78
+ * **Visual representation:**
79
+ *
80
+ * ![](https://user-images.githubusercontent.com/12958674/88806278-968f0680-d186-11ea-9cb5-8ef2606ffcc7.png)
81
+ */
82
+ mergeAudio(buffers: AudioBuffer[]): AudioBuffer {
83
+ const output = this._context.createBuffer(
84
+ this._maxNumberOfChannels(buffers),
85
+ this._sampleRate * this._maxDuration(buffers),
86
+ this._sampleRate
87
+ );
88
+
89
+ buffers.forEach((buffer) => {
90
+ for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {
91
+ const outputData = output.getChannelData(channelNumber);
92
+ const bufferData = buffer.getChannelData(channelNumber);
93
+
94
+ for (let i = buffer.getChannelData(channelNumber).length - 1; i >= 0; i--) {
95
+ outputData[i] += bufferData[i];
96
+ }
97
+
98
+ output.getChannelData(channelNumber).set(outputData);
99
+ }
100
+ });
101
+
102
+ return output;
103
+ }
104
+
105
+ /**
106
+ * Concatenates multiple AudioBuffers into a single AudioBuffer.
107
+ *
108
+ * **Visual representation:**
109
+ *
110
+ * ![](https://user-images.githubusercontent.com/12958674/88806297-9d1d7e00-d186-11ea-8cd2-c64cb0324845.png)
111
+ */
112
+ concatAudio(buffers: AudioBuffer[]): AudioBuffer {
113
+ const output = this._context.createBuffer(
114
+ this._maxNumberOfChannels(buffers),
115
+ this._totalLength(buffers),
116
+ this._sampleRate
117
+ );
118
+ let offset = 0;
119
+
120
+ buffers.forEach((buffer) => {
121
+ for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {
122
+ output.getChannelData(channelNumber).set(buffer.getChannelData(channelNumber), offset);
123
+ }
124
+
125
+ offset += buffer.length;
126
+ });
127
+
128
+ return output;
129
+ }
130
+
131
+ /**
132
+ * Pads a specified AudioBuffer with silence from a specified start time,
133
+ * for a specified length of time.
134
+ *
135
+ * Accepts float values as well as whole integers.
136
+ *
137
+ * @param buffer AudioBuffer to pad
138
+ * @param padStart Time to start padding (in seconds)
139
+ * @param seconds Duration to pad for (in seconds)
140
+ */
141
+ padAudio(buffer: AudioBuffer, padStart: number = 0, seconds: number = 0): AudioBuffer {
142
+ if (seconds === 0) return buffer;
143
+
144
+ if (padStart < 0) throw new Error('Crunker: Parameter "padStart" in padAudio must be positive');
145
+ if (seconds < 0) throw new Error('Crunker: Parameter "seconds" in padAudio must be positive');
146
+
147
+ const updatedBuffer = this._context.createBuffer(
148
+ buffer.numberOfChannels,
149
+ Math.ceil(buffer.length + seconds * buffer.sampleRate),
150
+ buffer.sampleRate
151
+ );
152
+
153
+ for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {
154
+ const channelData = buffer.getChannelData(channelNumber);
155
+ updatedBuffer
156
+ .getChannelData(channelNumber)
157
+ .set(channelData.subarray(0, Math.ceil(padStart * buffer.sampleRate) + 1), 0);
158
+
159
+ updatedBuffer
160
+ .getChannelData(channelNumber)
161
+ .set(
162
+ channelData.subarray(Math.ceil(padStart * buffer.sampleRate) + 2, updatedBuffer.length + 1),
163
+ Math.ceil((padStart + seconds) * buffer.sampleRate)
164
+ );
165
+ }
166
+
167
+ return updatedBuffer;
168
+ }
169
+
170
+ /**
171
+ * Plays the provided AudioBuffer in an AudioBufferSourceNode.
172
+ */
173
+ play(buffer: AudioBuffer): AudioBufferSourceNode {
174
+ const source = this._context.createBufferSource();
175
+
176
+ source.buffer = buffer;
177
+ source.connect(this._context.destination);
178
+ source.start();
179
+
180
+ return source;
181
+ }
182
+
183
+ /**
184
+ * Exports the specified AudioBuffer to a Blob, Object URI and HTMLAudioElement.
185
+ *
186
+ * Note that changing the MIME type does not change the actual file format. The
187
+ * file format will **always** be a WAVE file due to how audio is stored in the
188
+ * browser.
189
+ *
190
+ * @param buffer Buffer to export
191
+ * @param type MIME type (default: `audio/wav`)
192
+ */
193
+ export(buffer: AudioBuffer, type: string = 'audio/wav'): ExportedCrunkerAudio {
194
+ const recorded = this._interleave(buffer);
195
+ const dataview = this._writeHeaders(recorded);
196
+ const audioBlob = new Blob([dataview], { type });
197
+
198
+ return {
199
+ blob: audioBlob,
200
+ url: this._renderURL(audioBlob),
201
+ element: this._renderAudioElement(audioBlob),
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Downloads the provided Blob.
207
+ *
208
+ * @param blob Blob to download
209
+ * @param filename An optional file name to use for the download (default: `crunker`)
210
+ */
211
+ download(blob: Blob, filename: string = 'crunker'): HTMLAnchorElement {
212
+ const a = document.createElement('a');
213
+
214
+ a.style.display = 'none';
215
+ a.href = this._renderURL(blob);
216
+ a.download = `${filename}.${blob.type.split('/')[1]}`;
217
+ a.click();
218
+
219
+ return a;
220
+ }
221
+
222
+ /**
223
+ * Executes a callback if the browser does not support the Web Audio API.
224
+ *
225
+ * Returns the result of the callback, or `undefined` if the Web Audio API is supported.
226
+ *
227
+ * @param callback callback to run if the browser does not support the Web Audio API
228
+ */
229
+ notSupported<T>(callback: () => T): T | undefined {
230
+ return this._isSupported() ? undefined : callback();
231
+ }
232
+
233
+ /**
234
+ * Closes Crunker's internal AudioContext.
235
+ */
236
+ close(): this {
237
+ this._context.close();
238
+ return this;
239
+ }
240
+
241
+ /**
242
+ * Returns the largest duration of the longest AudioBuffer.
243
+ *
244
+ * @internal
245
+ */
246
+ private _maxDuration(buffers: AudioBuffer[]): number {
247
+ return Math.max(...buffers.map((buffer) => buffer.duration));
248
+ }
249
+
250
+ /**
251
+ * Returns the largest number of channels in an array of AudioBuffers.
252
+ *
253
+ * @internal
254
+ */
255
+ private _maxNumberOfChannels(buffers: AudioBuffer[]): number {
256
+ return Math.max(...buffers.map((buffer) => buffer.numberOfChannels));
257
+ }
258
+
259
+ /**
260
+ * Returns the sum of the lengths of an array of AudioBuffers.
261
+ *
262
+ * @internal
263
+ */
264
+ private _totalLength(buffers: AudioBuffer[]): number {
265
+ return buffers.map((buffer) => buffer.length).reduce((a, b) => a + b, 0);
266
+ }
267
+
268
+ /**
269
+ * Returns whether the browser supports the Web Audio API.
270
+ *
271
+ * @internal
272
+ */
273
+ private _isSupported(): boolean {
274
+ return 'AudioContext' in window || 'webkitAudioContext' in window || 'mozAudioContext' in window;
275
+ }
276
+
277
+ /**
278
+ * Writes the WAV headers for the specified Float32Array.
279
+ *
280
+ * Returns a DataView containing the WAV headers and file content.
281
+ *
282
+ * @internal
283
+ */
284
+ private _writeHeaders(buffer: Float32Array): DataView {
285
+ const arrayBuffer = new ArrayBuffer(44 + buffer.length * 2);
286
+ const view = new DataView(arrayBuffer);
287
+
288
+ this._writeString(view, 0, 'RIFF');
289
+ view.setUint32(4, 32 + buffer.length * 2, true);
290
+ this._writeString(view, 8, 'WAVE');
291
+ this._writeString(view, 12, 'fmt ');
292
+ view.setUint32(16, 16, true);
293
+ view.setUint16(20, 1, true);
294
+ view.setUint16(22, 2, true);
295
+ view.setUint32(24, this._sampleRate, true);
296
+ view.setUint32(28, this._sampleRate * 4, true);
297
+ view.setUint16(32, 4, true);
298
+ view.setUint16(34, 16, true);
299
+ this._writeString(view, 36, 'data');
300
+ view.setUint32(40, buffer.length * 2, true);
301
+
302
+ return this._floatTo16BitPCM(view, buffer, 44);
303
+ }
304
+
305
+ /**
306
+ * Converts a Float32Array to 16-bit PCM.
307
+ *
308
+ * @internal
309
+ */
310
+ private _floatTo16BitPCM(dataview: DataView, buffer: Float32Array, offset: number): DataView {
311
+ for (let i = 0; i < buffer.length; i++, offset += 2) {
312
+ const tmp = Math.max(-1, Math.min(1, buffer[i]));
313
+ dataview.setInt16(offset, tmp < 0 ? tmp * 0x8000 : tmp * 0x7fff, true);
314
+ }
315
+
316
+ return dataview;
317
+ }
318
+
319
+ /**
320
+ * Writes a string to a DataView at the specified offset.
321
+ *
322
+ * @internal
323
+ */
324
+ private _writeString(dataview: DataView, offset: number, header: string): void {
325
+ for (let i = 0; i < header.length; i++) {
326
+ dataview.setUint8(offset + i, header.charCodeAt(i));
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Converts an AudioBuffer to a Float32Array.
332
+ *
333
+ * @internal
334
+ */
335
+ private _interleave(input: AudioBuffer): Float32Array {
336
+ const buffer = input.getChannelData(0),
337
+ length = buffer.length * 2,
338
+ result = new Float32Array(length);
339
+
340
+ let index = 0,
341
+ inputIndex = 0;
342
+
343
+ while (index < length) {
344
+ result[index++] = buffer[inputIndex];
345
+ result[index++] = buffer[inputIndex];
346
+ inputIndex++;
347
+ }
348
+ return result;
349
+ }
350
+
351
+ /**
352
+ * Creates an HTMLAudioElement whose source is the specified Blob.
353
+ *
354
+ * @internal
355
+ */
356
+ private _renderAudioElement(blob: Blob): HTMLAudioElement {
357
+ const audio = document.createElement('audio');
358
+
359
+ audio.controls = true;
360
+ audio.src = this._renderURL(blob);
361
+
362
+ return audio;
363
+ }
364
+
365
+ /**
366
+ * Creates an Object URL for the specified Blob.
367
+ *
368
+ * @internal
369
+ */
370
+ private _renderURL(blob: Blob): string {
371
+ return (window.URL || window.webkitURL).createObjectURL(blob);
372
+ }
373
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,63 @@
1
+
2
+ {
3
+ "compilerOptions": {
4
+ /* Basic Options */
5
+ "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
6
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
7
+ // "lib": [], /* Specify library files to be included in the compilation. */
8
+ // "allowJs": true, /* Allow javascript files to be compiled. */
9
+ // "checkJs": true, /* Report errors in .js files. */
10
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11
+ "declaration": true, /* Generates corresponding '.d.ts' file. */
12
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13
+ // "sourceMap": true, /* Generates corresponding '.map' file. */
14
+ // "outFile": "./", /* Concatenate and emit output to single file. */
15
+ "outDir": "dist", /* Redirect output structure to the directory. */
16
+ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17
+ // "composite": true, /* Enable project compilation */
18
+ // "removeComments": true, /* Do not emit comments to output. */
19
+ // "noEmit": true, /* Do not emit outputs. */
20
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
21
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
22
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
23
+
24
+ /* Strict Type-Checking Options */
25
+ "strict": true, /* Enable all strict type-checking options. */
26
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
27
+ // "strictNullChecks": true, /* Enable strict null checks. */
28
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
29
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
30
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
31
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
32
+
33
+ /* Additional Checks */
34
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
35
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
36
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
37
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
38
+
39
+ /* Module Resolution Options */
40
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
41
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
42
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44
+ // "typeRoots": [], /* List of folders to include type definitions from. */
45
+ // "types": [], /* Type declaration files to be included in compilation. */
46
+ "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
47
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
48
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
49
+
50
+ /* Source Map Options */
51
+ // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
52
+ // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
53
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
54
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
55
+
56
+ /* Experimental Options */
57
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
58
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
59
+
60
+ /* Advanced Options */
61
+ // "declarationDir": "lib" /* Output directory for generated declaration files. */
62
+ }
63
+ }
package/webpack.config.js CHANGED
@@ -1,35 +1,43 @@
1
- const webpack = require("webpack");
2
- const TerserPlugin = require("terser-webpack-plugin");
1
+ const webpack = require('webpack');
2
+ const TerserPlugin = require('terser-webpack-plugin');
3
3
 
4
4
  module.exports = {
5
- mode: "production",
6
- context: __dirname + "/src",
7
- entry: "./crunker.js",
5
+ mode: 'production',
6
+ context: __dirname + '/src',
7
+ entry: './crunker.ts',
8
8
  output: {
9
- path: __dirname + "/dist",
10
- filename: "crunker.js",
11
- library: "Crunker",
12
- libraryTarget: "umd",
9
+ path: __dirname + '/dist',
10
+ filename: 'crunker.js',
11
+ library: 'Crunker',
12
+ libraryTarget: 'umd',
13
13
  umdNamedDefine: true,
14
14
  },
15
+ devtool: 'source-map',
15
16
  module: {
16
17
  rules: [
17
18
  {
18
- test: /\.js$/,
19
+ test: /\.ts$/,
19
20
  exclude: /node_modules/,
20
- loader: "babel-loader",
21
+ loader: 'babel-loader',
21
22
  query: {
22
- presets: ["es2015"],
23
+ presets: [
24
+ [
25
+ '@babel/preset-env',
26
+ { exclude: ['@babel/plugin-transform-regenerator', '@babel/plugin-transform-async-to-generator'] },
27
+ ],
28
+ '@babel/preset-typescript',
29
+ ],
23
30
  },
24
31
  },
25
32
  ],
26
33
  },
27
34
  optimization: {
35
+ minimize: true,
28
36
  minimizer: [new TerserPlugin()],
29
37
  },
30
38
  plugins: [
31
39
  new webpack.DefinePlugin({
32
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
40
+ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
33
41
  }),
34
42
  ],
35
43
  };
@@ -9,31 +9,37 @@ module.exports = {
9
9
  devtool: 'inline-source-map',
10
10
  output: {
11
11
  path: testDir,
12
- filename: "test.bundle.js",
13
- library: "Crunker",
14
- libraryTarget: "umd",
15
- umdNamedDefine: true
12
+ filename: 'test.bundle.js',
13
+ library: 'Crunker',
14
+ libraryTarget: 'umd',
15
+ umdNamedDefine: true,
16
16
  },
17
17
  resolve: {
18
- alias: {
19
- 'crunker': path.resolve(__dirname, 'src/crunker.js')
20
- }
18
+ alias: {
19
+ crunker: path.resolve(__dirname, 'src/crunker.ts'),
20
+ },
21
21
  },
22
22
  module: {
23
23
  rules: [
24
24
  {
25
- test: /\.js$/,
25
+ test: /\.(j|t)s$/,
26
26
  exclude: /node_modules/,
27
27
  loader: 'babel-loader',
28
28
  query: {
29
- presets: ['es2015']
30
- }
31
- }
32
- ]
29
+ presets: [
30
+ [
31
+ '@babel/preset-env',
32
+ { exclude: ['@babel/plugin-transform-regenerator', '@babel/plugin-transform-async-to-generator'] },
33
+ ],
34
+ '@babel/preset-typescript',
35
+ ],
36
+ },
37
+ },
38
+ ],
33
39
  },
34
40
  plugins: [
35
41
  new webpack.DefinePlugin({
36
- 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
37
- })
38
- ]
39
- };
42
+ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
43
+ }),
44
+ ],
45
+ };