wavesurfer.js 7.0.0-alpha.9 → 7.0.0-beta.10

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.
Files changed (55) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +137 -20
  3. package/dist/base-plugin.d.ts +6 -4
  4. package/dist/base-plugin.js +9 -3
  5. package/dist/decoder.d.ts +8 -7
  6. package/dist/decoder.js +43 -38
  7. package/dist/draggable.d.ts +1 -0
  8. package/dist/draggable.js +59 -0
  9. package/dist/event-emitter.d.ts +16 -10
  10. package/dist/event-emitter.js +38 -16
  11. package/dist/fetcher.d.ts +6 -3
  12. package/dist/fetcher.js +9 -15
  13. package/dist/player.d.ts +31 -11
  14. package/dist/player.js +58 -31
  15. package/dist/plugins/envelope.d.ts +71 -0
  16. package/dist/plugins/envelope.js +326 -0
  17. package/dist/plugins/envelope.min.cjs +1 -0
  18. package/dist/plugins/minimap.d.ts +39 -0
  19. package/dist/plugins/minimap.js +114 -0
  20. package/dist/plugins/minimap.min.cjs +1 -0
  21. package/dist/plugins/record.d.ts +28 -0
  22. package/dist/plugins/record.js +132 -0
  23. package/dist/plugins/record.min.cjs +1 -0
  24. package/dist/plugins/regions.d.ts +84 -43
  25. package/dist/plugins/regions.js +330 -195
  26. package/dist/plugins/regions.min.cjs +1 -0
  27. package/dist/plugins/spectrogram-fft.d.ts +9 -0
  28. package/dist/plugins/spectrogram-fft.js +150 -0
  29. package/dist/plugins/spectrogram.d.ts +72 -0
  30. package/dist/plugins/spectrogram.js +341 -0
  31. package/dist/plugins/spectrogram.min.cjs +1 -0
  32. package/dist/plugins/timeline.d.ts +25 -9
  33. package/dist/plugins/timeline.js +65 -24
  34. package/dist/plugins/timeline.min.cjs +1 -0
  35. package/dist/renderer.d.ts +32 -26
  36. package/dist/renderer.js +363 -167
  37. package/dist/timer.d.ts +1 -1
  38. package/dist/wavesurfer.d.ts +154 -0
  39. package/dist/wavesurfer.js +230 -0
  40. package/dist/wavesurfer.min.cjs +1 -0
  41. package/package.json +61 -28
  42. package/dist/index.d.ts +0 -117
  43. package/dist/index.js +0 -227
  44. package/dist/player-webaudio.d.ts +0 -8
  45. package/dist/player-webaudio.js +0 -32
  46. package/dist/plugins/multitrack.d.ts +0 -44
  47. package/dist/plugins/multitrack.js +0 -260
  48. package/dist/plugins/xmultitrack.d.ts +0 -44
  49. package/dist/plugins/xmultitrack.js +0 -260
  50. package/dist/react/useWavesurfer.d.ts +0 -5
  51. package/dist/react/useWavesurfer.js +0 -20
  52. package/dist/wavesurfer.Multitrack.min.js +0 -1
  53. package/dist/wavesurfer.Regions.min.js +0 -1
  54. package/dist/wavesurfer.Timeline.min.js +0 -1
  55. package/dist/wavesurfer.min.js +0 -1
@@ -0,0 +1,150 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Calculate FFT - Based on https://github.com/corbanbrook/dsp.js
4
+ *
5
+ * @param {Number} bufferSize Buffer size
6
+ * @param {Number} sampleRate Sample rate
7
+ * @param {Function} windowFunc Window function
8
+ * @param {Number} alpha Alpha channel
9
+ */
10
+ export default function FFT(bufferSize, sampleRate, windowFunc, alpha) {
11
+ this.bufferSize = bufferSize;
12
+ this.sampleRate = sampleRate;
13
+ this.bandwidth = (2 / bufferSize) * (sampleRate / 2);
14
+ this.sinTable = new Float32Array(bufferSize);
15
+ this.cosTable = new Float32Array(bufferSize);
16
+ this.windowValues = new Float32Array(bufferSize);
17
+ this.reverseTable = new Uint32Array(bufferSize);
18
+ this.peakBand = 0;
19
+ this.peak = 0;
20
+ var i;
21
+ switch (windowFunc) {
22
+ case 'bartlett':
23
+ for (i = 0; i < bufferSize; i++) {
24
+ this.windowValues[i] = (2 / (bufferSize - 1)) * ((bufferSize - 1) / 2 - Math.abs(i - (bufferSize - 1) / 2));
25
+ }
26
+ break;
27
+ case 'bartlettHann':
28
+ for (i = 0; i < bufferSize; i++) {
29
+ this.windowValues[i] =
30
+ 0.62 - 0.48 * Math.abs(i / (bufferSize - 1) - 0.5) - 0.38 * Math.cos((Math.PI * 2 * i) / (bufferSize - 1));
31
+ }
32
+ break;
33
+ case 'blackman':
34
+ alpha = alpha || 0.16;
35
+ for (i = 0; i < bufferSize; i++) {
36
+ this.windowValues[i] =
37
+ (1 - alpha) / 2 -
38
+ 0.5 * Math.cos((Math.PI * 2 * i) / (bufferSize - 1)) +
39
+ (alpha / 2) * Math.cos((4 * Math.PI * i) / (bufferSize - 1));
40
+ }
41
+ break;
42
+ case 'cosine':
43
+ for (i = 0; i < bufferSize; i++) {
44
+ this.windowValues[i] = Math.cos((Math.PI * i) / (bufferSize - 1) - Math.PI / 2);
45
+ }
46
+ break;
47
+ case 'gauss':
48
+ alpha = alpha || 0.25;
49
+ for (i = 0; i < bufferSize; i++) {
50
+ this.windowValues[i] = Math.pow(Math.E, -0.5 * Math.pow((i - (bufferSize - 1) / 2) / ((alpha * (bufferSize - 1)) / 2), 2));
51
+ }
52
+ break;
53
+ case 'hamming':
54
+ for (i = 0; i < bufferSize; i++) {
55
+ this.windowValues[i] = 0.54 - 0.46 * Math.cos((Math.PI * 2 * i) / (bufferSize - 1));
56
+ }
57
+ break;
58
+ case 'hann':
59
+ case undefined:
60
+ for (i = 0; i < bufferSize; i++) {
61
+ this.windowValues[i] = 0.5 * (1 - Math.cos((Math.PI * 2 * i) / (bufferSize - 1)));
62
+ }
63
+ break;
64
+ case 'lanczoz':
65
+ for (i = 0; i < bufferSize; i++) {
66
+ this.windowValues[i] =
67
+ Math.sin(Math.PI * ((2 * i) / (bufferSize - 1) - 1)) / (Math.PI * ((2 * i) / (bufferSize - 1) - 1));
68
+ }
69
+ break;
70
+ case 'rectangular':
71
+ for (i = 0; i < bufferSize; i++) {
72
+ this.windowValues[i] = 1;
73
+ }
74
+ break;
75
+ case 'triangular':
76
+ for (i = 0; i < bufferSize; i++) {
77
+ this.windowValues[i] = (2 / bufferSize) * (bufferSize / 2 - Math.abs(i - (bufferSize - 1) / 2));
78
+ }
79
+ break;
80
+ default:
81
+ throw Error("No such window function '" + windowFunc + "'");
82
+ }
83
+ var limit = 1;
84
+ var bit = bufferSize >> 1;
85
+ var i;
86
+ while (limit < bufferSize) {
87
+ for (i = 0; i < limit; i++) {
88
+ this.reverseTable[i + limit] = this.reverseTable[i] + bit;
89
+ }
90
+ limit = limit << 1;
91
+ bit = bit >> 1;
92
+ }
93
+ for (i = 0; i < bufferSize; i++) {
94
+ this.sinTable[i] = Math.sin(-Math.PI / i);
95
+ this.cosTable[i] = Math.cos(-Math.PI / i);
96
+ }
97
+ this.calculateSpectrum = function (buffer) {
98
+ // Locally scope variables for speed up
99
+ var bufferSize = this.bufferSize, cosTable = this.cosTable, sinTable = this.sinTable, reverseTable = this.reverseTable, real = new Float32Array(bufferSize), imag = new Float32Array(bufferSize), bSi = 2 / this.bufferSize, sqrt = Math.sqrt, rval, ival, mag, spectrum = new Float32Array(bufferSize / 2);
100
+ var k = Math.floor(Math.log(bufferSize) / Math.LN2);
101
+ if (Math.pow(2, k) !== bufferSize) {
102
+ throw 'Invalid buffer size, must be a power of 2.';
103
+ }
104
+ if (bufferSize !== buffer.length) {
105
+ throw ('Supplied buffer is not the same size as defined FFT. FFT Size: ' +
106
+ bufferSize +
107
+ ' Buffer Size: ' +
108
+ buffer.length);
109
+ }
110
+ var halfSize = 1, phaseShiftStepReal, phaseShiftStepImag, currentPhaseShiftReal, currentPhaseShiftImag, off, tr, ti, tmpReal;
111
+ for (var i = 0; i < bufferSize; i++) {
112
+ real[i] = buffer[reverseTable[i]] * this.windowValues[reverseTable[i]];
113
+ imag[i] = 0;
114
+ }
115
+ while (halfSize < bufferSize) {
116
+ phaseShiftStepReal = cosTable[halfSize];
117
+ phaseShiftStepImag = sinTable[halfSize];
118
+ currentPhaseShiftReal = 1;
119
+ currentPhaseShiftImag = 0;
120
+ for (var fftStep = 0; fftStep < halfSize; fftStep++) {
121
+ var i = fftStep;
122
+ while (i < bufferSize) {
123
+ off = i + halfSize;
124
+ tr = currentPhaseShiftReal * real[off] - currentPhaseShiftImag * imag[off];
125
+ ti = currentPhaseShiftReal * imag[off] + currentPhaseShiftImag * real[off];
126
+ real[off] = real[i] - tr;
127
+ imag[off] = imag[i] - ti;
128
+ real[i] += tr;
129
+ imag[i] += ti;
130
+ i += halfSize << 1;
131
+ }
132
+ tmpReal = currentPhaseShiftReal;
133
+ currentPhaseShiftReal = tmpReal * phaseShiftStepReal - currentPhaseShiftImag * phaseShiftStepImag;
134
+ currentPhaseShiftImag = tmpReal * phaseShiftStepImag + currentPhaseShiftImag * phaseShiftStepReal;
135
+ }
136
+ halfSize = halfSize << 1;
137
+ }
138
+ for (var i = 0, N = bufferSize / 2; i < N; i++) {
139
+ rval = real[i];
140
+ ival = imag[i];
141
+ mag = bSi * sqrt(rval * rval + ival * ival);
142
+ if (mag > this.peak) {
143
+ this.peakBand = i;
144
+ this.peak = mag;
145
+ }
146
+ spectrum[i] = mag;
147
+ }
148
+ return spectrum;
149
+ };
150
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Spectrogram plugin
3
+ *
4
+ * Render a spectrogram visualisation of the audio.
5
+ *
6
+ * @author Pavel Denisov (https://github.com/akreal)
7
+ * @see https://github.com/wavesurfer-js/wavesurfer.js/pull/337
8
+ *
9
+ * @example
10
+ * // ... initialising wavesurfer with the plugin
11
+ * var wavesurfer = WaveSurfer.create({
12
+ * // wavesurfer options ...
13
+ * plugins: [
14
+ * SpectrogramPlugin.create({
15
+ * // plugin options ...
16
+ * })
17
+ * ]
18
+ * });
19
+ */
20
+ import BasePlugin from '../base-plugin.js';
21
+ export type SpectrogramPluginOptions = {
22
+ /** Selector of element or element in which to render */
23
+ container: string | HTMLElement;
24
+ /** Number of samples to fetch to FFT. Must be a power of 2. */
25
+ fftSamples?: number;
26
+ /** Height of the spectrogram view in CSS pixels */
27
+ height?: number;
28
+ /** Set to true to display frequency labels. */
29
+ labels?: boolean;
30
+ labelsBackground?: string;
31
+ labelsColor?: string;
32
+ labelsHzColor?: string;
33
+ /** Size of the overlapping window. Must be < fftSamples. Auto deduced from canvas size by default. */
34
+ noverlap?: number;
35
+ /** The window function to be used. */
36
+ windowFunc?: 'bartlett' | 'bartlettHann' | 'blackman' | 'cosine' | 'gauss' | 'hamming' | 'hann' | 'lanczoz' | 'rectangular' | 'triangular';
37
+ /** Some window functions have this extra value. (Between 0 and 1) */
38
+ alpha?: number;
39
+ /** Min frequency to scale spectrogram. */
40
+ frequencyMin?: number;
41
+ /** Max frequency to scale spectrogram. Set this to samplerate/2 to draw whole range of spectrogram. */
42
+ frequencyMax?: number;
43
+ /**
44
+ * A 256 long array of 4-element arrays. Each entry should contain a float between 0 and 1 and specify r, g, b, and alpha.
45
+ * Each entry should contain a float between 0 and 1 and specify r, g, b, and alpha.
46
+ */
47
+ colorMap?: number[][];
48
+ };
49
+ export type SpectrogramPluginEvents = {
50
+ ready: [];
51
+ click: [relativeX: number];
52
+ };
53
+ export default class SpectrogramPlugin extends BasePlugin<SpectrogramPluginEvents, SpectrogramPluginOptions> {
54
+ static create(options?: SpectrogramPluginOptions): SpectrogramPlugin;
55
+ utils: {
56
+ style: (el: HTMLElement, styles: Record<string, string>) => CSSStyleDeclaration & Record<string, string>;
57
+ };
58
+ constructor(options: SpectrogramPluginOptions);
59
+ onInit(): void;
60
+ destroy(): void;
61
+ createWrapper(): void;
62
+ _wrapperClickHandler(event: any): void;
63
+ createCanvas(): void;
64
+ render(): void;
65
+ drawSpectrogram: (frequenciesData: any) => void;
66
+ getFrequencies(callback: any): void;
67
+ loadFrequenciesData(url: any): Promise<void>;
68
+ freqType(freq: any): string | number;
69
+ unitType(freq: any): "KHz" | "Hz";
70
+ loadLabels(bgFill: any, fontSizeFreq: any, fontSizeUnit: any, fontType: any, textColorFreq: any, textColorUnit: any, textAlign: any, container: any): void;
71
+ resample(oldMatrix: any): Uint8Array[];
72
+ }
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Spectrogram plugin
3
+ *
4
+ * Render a spectrogram visualisation of the audio.
5
+ *
6
+ * @author Pavel Denisov (https://github.com/akreal)
7
+ * @see https://github.com/wavesurfer-js/wavesurfer.js/pull/337
8
+ *
9
+ * @example
10
+ * // ... initialising wavesurfer with the plugin
11
+ * var wavesurfer = WaveSurfer.create({
12
+ * // wavesurfer options ...
13
+ * plugins: [
14
+ * SpectrogramPlugin.create({
15
+ * // plugin options ...
16
+ * })
17
+ * ]
18
+ * });
19
+ */
20
+ // @ts-nocheck
21
+ import BasePlugin from '../base-plugin.js';
22
+ import FFT from './spectrogram-fft.js';
23
+ export default class SpectrogramPlugin extends BasePlugin {
24
+ static create(options) {
25
+ return new SpectrogramPlugin(options || {});
26
+ }
27
+ constructor(options) {
28
+ super(options);
29
+ this.utils = {
30
+ style: (el, styles) => Object.assign(el.style, styles),
31
+ };
32
+ this.drawSpectrogram = (frequenciesData) => {
33
+ if (!isNaN(frequenciesData[0][0])) {
34
+ // data is 1ch [sample, freq] format
35
+ // to [channel, sample, freq] format
36
+ frequenciesData = [frequenciesData];
37
+ }
38
+ const spectrCc = this.spectrCc;
39
+ const height = this.height;
40
+ const width = this.width;
41
+ const freqFrom = this.buffer.sampleRate / 2;
42
+ const freqMin = this.frequencyMin;
43
+ const freqMax = this.frequencyMax;
44
+ if (!spectrCc) {
45
+ return;
46
+ }
47
+ for (let c = 0; c < frequenciesData.length; c++) {
48
+ // for each channel
49
+ const pixels = this.resample(frequenciesData[c]);
50
+ const imageData = new ImageData(width, height);
51
+ for (let i = 0; i < pixels.length; i++) {
52
+ for (let j = 0; j < pixels[i].length; j++) {
53
+ const colorMap = this.colorMap[pixels[i][j]];
54
+ const redIndex = ((height - j) * width + i) * 4;
55
+ imageData.data[redIndex] = colorMap[0] * 255;
56
+ imageData.data[redIndex + 1] = colorMap[1] * 255;
57
+ imageData.data[redIndex + 2] = colorMap[2] * 255;
58
+ imageData.data[redIndex + 3] = colorMap[3] * 255;
59
+ }
60
+ }
61
+ // scale and stack spectrograms
62
+ createImageBitmap(imageData).then((renderer) => {
63
+ spectrCc.drawImage(renderer, 0, height * (1 - freqMax / freqFrom), // source x, y
64
+ width, (height * (freqMax - freqMin)) / freqFrom, // source width, height
65
+ 0, height * c, // destination x, y
66
+ width, height);
67
+ });
68
+ }
69
+ this.emit('ready');
70
+ };
71
+ this.frequenciesDataUrl = options.frequenciesDataUrl;
72
+ this.container =
73
+ 'string' == typeof options.container ? document.querySelector(options.container) : options.container;
74
+ if (options.colorMap) {
75
+ if (options.colorMap.length < 256) {
76
+ throw new Error('Colormap must contain 256 elements');
77
+ }
78
+ for (let i = 0; i < options.colorMap.length; i++) {
79
+ const cmEntry = options.colorMap[i];
80
+ if (cmEntry.length !== 4) {
81
+ throw new Error('ColorMap entries must contain 4 values');
82
+ }
83
+ }
84
+ this.colorMap = options.colorMap;
85
+ }
86
+ else {
87
+ this.colorMap = [];
88
+ for (let i = 0; i < 256; i++) {
89
+ const val = (255 - i) / 256;
90
+ this.colorMap.push([val, val, val, 1]);
91
+ }
92
+ }
93
+ this.fftSamples = options.fftSamples || 512;
94
+ this.height = options.height || this.fftSamples / 2;
95
+ this.noverlap = options.noverlap;
96
+ this.windowFunc = options.windowFunc;
97
+ this.alpha = options.alpha;
98
+ this.channels = 1;
99
+ // Getting file's original samplerate is difficult(#1248).
100
+ // So set 12kHz default to render like wavesurfer.js 5.x.
101
+ this.frequencyMin = options.frequencyMin || 0;
102
+ this.frequencyMax = options.frequencyMax || 0;
103
+ this.createWrapper();
104
+ this.createCanvas();
105
+ }
106
+ onInit() {
107
+ this.container = this.container || this.wavesurfer.getWrapper();
108
+ this.container.appendChild(this.wrapper);
109
+ if (this.wavesurfer.options.fillParent) {
110
+ this.utils.style(this.wrapper, {
111
+ width: '100%',
112
+ overflowX: 'hidden',
113
+ overflowY: 'hidden',
114
+ });
115
+ }
116
+ this.width = this.wavesurfer.getWrapper().offsetWidth;
117
+ this.subscriptions.push(this.wavesurfer.on('redraw', () => this.render()));
118
+ }
119
+ destroy() {
120
+ this.unAll();
121
+ this.wavesurfer.un('ready', this._onReady);
122
+ this.wavesurfer.un('redraw', this._onRender);
123
+ this.wavesurfer = null;
124
+ this.util = null;
125
+ this.options = null;
126
+ if (this.wrapper) {
127
+ this.wrapper.remove();
128
+ this.wrapper = null;
129
+ }
130
+ }
131
+ createWrapper() {
132
+ this.wrapper = document.createElement('div');
133
+ this.utils.style(this.wrapper, {
134
+ display: 'block',
135
+ position: 'relative',
136
+ userSelect: 'none',
137
+ webkitUserSelect: 'none',
138
+ height: `${this.height * this.channels}px`,
139
+ });
140
+ // if labels are active
141
+ if (this.options.labels) {
142
+ const labelsEl = document.createElement('canvas');
143
+ labelsEl.setAttribute('part', 'spec-labels');
144
+ labelsEl.classList.add('spec-labels');
145
+ this.utils.style(labelsEl, {
146
+ position: 'absolute',
147
+ zIndex: 9,
148
+ width: '55px',
149
+ height: '100%',
150
+ });
151
+ this.wrapper.appendChild(labelsEl);
152
+ this.labelsEl = labelsEl;
153
+ }
154
+ this.wrapper.addEventListener('click', this._onWrapperClick);
155
+ }
156
+ _wrapperClickHandler(event) {
157
+ event.preventDefault();
158
+ const relX = 'offsetX' in event ? event.offsetX : event.layerX;
159
+ this.emit('click', relX / this.width || 0);
160
+ }
161
+ createCanvas() {
162
+ const canvas = document.createElement('canvas');
163
+ this.wrapper.appendChild(canvas);
164
+ this.spectrCc = canvas.getContext('2d');
165
+ this.utils.style(canvas, {
166
+ position: 'absolute',
167
+ left: 0,
168
+ top: 0,
169
+ width: '100%',
170
+ height: '100%',
171
+ zIndex: 4,
172
+ });
173
+ this.canvas = canvas;
174
+ }
175
+ render() {
176
+ this.canvas.width = this.width;
177
+ this.canvas.height = this.height;
178
+ if (this.frequenciesDataUrl) {
179
+ this.loadFrequenciesData(this.frequenciesDataUrl);
180
+ }
181
+ else {
182
+ this.getFrequencies(this.drawSpectrogram);
183
+ }
184
+ this.loadLabels(this.options.labelsBackground || 'rgba(68,68,68,0.5)', '12px', '10px', '', this.options.labelsColor || '#fff', this.options.labelsHzColor || this.options.labelsColor || '#f7f7f7', 'center', '#specLabels');
185
+ }
186
+ getFrequencies(callback) {
187
+ const fftSamples = this.fftSamples;
188
+ const buffer = this.wavesurfer.getDecodedData();
189
+ const channels = this.channels;
190
+ this.frequencyMax = this.frequencyMax || buffer.sampleRate / 2;
191
+ if (!buffer)
192
+ return;
193
+ this.buffer = buffer;
194
+ // This may differ from file samplerate. Browser resamples audio.
195
+ const sampleRate = buffer.sampleRate;
196
+ const frequencies = [];
197
+ let noverlap = this.noverlap;
198
+ if (!noverlap) {
199
+ const uniqueSamplesPerPx = buffer.length / this.canvas.width;
200
+ noverlap = Math.max(0, Math.round(fftSamples - uniqueSamplesPerPx));
201
+ }
202
+ const fft = new FFT(fftSamples, sampleRate, this.windowFunc, this.alpha);
203
+ for (let c = 0; c < channels; c++) {
204
+ // for each channel
205
+ const channelData = buffer.getChannelData(c);
206
+ const channelFreq = [];
207
+ let currentOffset = 0;
208
+ while (currentOffset + fftSamples < channelData.length) {
209
+ const segment = channelData.slice(currentOffset, currentOffset + fftSamples);
210
+ const spectrum = fft.calculateSpectrum(segment);
211
+ const array = new Uint8Array(fftSamples / 2);
212
+ let j;
213
+ for (j = 0; j < fftSamples / 2; j++) {
214
+ array[j] = Math.max(-255, Math.log10(spectrum[j]) * 45);
215
+ }
216
+ channelFreq.push(array);
217
+ // channelFreq: [sample, freq]
218
+ currentOffset += fftSamples - noverlap;
219
+ }
220
+ frequencies.push(channelFreq);
221
+ // frequencies: [channel, sample, freq]
222
+ }
223
+ callback(frequencies, this);
224
+ }
225
+ loadFrequenciesData(url) {
226
+ return fetch(url)
227
+ .then((response) => response.json())
228
+ .then(this.drawSpectrogram);
229
+ }
230
+ freqType(freq) {
231
+ return freq >= 1000 ? (freq / 1000).toFixed(1) : Math.round(freq);
232
+ }
233
+ unitType(freq) {
234
+ return freq >= 1000 ? 'KHz' : 'Hz';
235
+ }
236
+ loadLabels(bgFill, fontSizeFreq, fontSizeUnit, fontType, textColorFreq, textColorUnit, textAlign, container) {
237
+ const frequenciesHeight = this.height;
238
+ bgFill = bgFill || 'rgba(68,68,68,0)';
239
+ fontSizeFreq = fontSizeFreq || '12px';
240
+ fontSizeUnit = fontSizeUnit || '10px';
241
+ fontType = fontType || 'Helvetica';
242
+ textColorFreq = textColorFreq || '#fff';
243
+ textColorUnit = textColorUnit || '#fff';
244
+ textAlign = textAlign || 'center';
245
+ container = container || '#specLabels';
246
+ const bgWidth = 55;
247
+ const getMaxY = frequenciesHeight || 512;
248
+ const labelIndex = 5 * (getMaxY / 256);
249
+ const freqStart = this.frequencyMin;
250
+ const step = (this.frequencyMax - freqStart) / labelIndex;
251
+ // prepare canvas element for labels
252
+ const ctx = this.labelsEl.getContext('2d');
253
+ const dispScale = window.devicePixelRatio;
254
+ this.labelsEl.height = this.height * this.channels * dispScale;
255
+ this.labelsEl.width = bgWidth * dispScale;
256
+ ctx.scale(dispScale, dispScale);
257
+ if (!ctx) {
258
+ return;
259
+ }
260
+ for (let c = 0; c < this.channels; c++) {
261
+ // for each channel
262
+ // fill background
263
+ ctx.fillStyle = bgFill;
264
+ ctx.fillRect(0, c * getMaxY, bgWidth, (1 + c) * getMaxY);
265
+ ctx.fill();
266
+ let i;
267
+ // render labels
268
+ for (i = 0; i <= labelIndex; i++) {
269
+ ctx.textAlign = textAlign;
270
+ ctx.textBaseline = 'middle';
271
+ const freq = freqStart + step * i;
272
+ const label = this.freqType(freq);
273
+ const units = this.unitType(freq);
274
+ const yLabelOffset = 2;
275
+ const x = 16;
276
+ let y;
277
+ if (i == 0) {
278
+ y = (1 + c) * getMaxY + i - 10;
279
+ // unit label
280
+ ctx.fillStyle = textColorUnit;
281
+ ctx.font = fontSizeUnit + ' ' + fontType;
282
+ ctx.fillText(units, x + 24, y);
283
+ // freq label
284
+ ctx.fillStyle = textColorFreq;
285
+ ctx.font = fontSizeFreq + ' ' + fontType;
286
+ ctx.fillText(label, x, y);
287
+ }
288
+ else {
289
+ y = (1 + c) * getMaxY - i * 50 + yLabelOffset;
290
+ // unit label
291
+ ctx.fillStyle = textColorUnit;
292
+ ctx.font = fontSizeUnit + ' ' + fontType;
293
+ ctx.fillText(units, x + 24, y);
294
+ // freq label
295
+ ctx.fillStyle = textColorFreq;
296
+ ctx.font = fontSizeFreq + ' ' + fontType;
297
+ ctx.fillText(label, x, y);
298
+ }
299
+ }
300
+ }
301
+ }
302
+ resample(oldMatrix) {
303
+ const columnsNumber = this.width;
304
+ const newMatrix = [];
305
+ const oldPiece = 1 / oldMatrix.length;
306
+ const newPiece = 1 / columnsNumber;
307
+ let i;
308
+ for (i = 0; i < columnsNumber; i++) {
309
+ const column = new Array(oldMatrix[0].length);
310
+ let j;
311
+ for (j = 0; j < oldMatrix.length; j++) {
312
+ const oldStart = j * oldPiece;
313
+ const oldEnd = oldStart + oldPiece;
314
+ const newStart = i * newPiece;
315
+ const newEnd = newStart + newPiece;
316
+ const overlap = oldEnd <= newStart || newEnd <= oldStart
317
+ ? 0
318
+ : Math.min(Math.max(oldEnd, newStart), Math.max(newEnd, oldStart)) -
319
+ Math.max(Math.min(oldEnd, newStart), Math.min(newEnd, oldStart));
320
+ let k;
321
+ /* eslint-disable max-depth */
322
+ if (overlap > 0) {
323
+ for (k = 0; k < oldMatrix[0].length; k++) {
324
+ if (column[k] == null) {
325
+ column[k] = 0;
326
+ }
327
+ column[k] += (overlap / newPiece) * oldMatrix[j][k];
328
+ }
329
+ }
330
+ /* eslint-enable max-depth */
331
+ }
332
+ const intColumn = new Uint8Array(oldMatrix[0].length);
333
+ let m;
334
+ for (m = 0; m < oldMatrix[0].length; m++) {
335
+ intColumn[m] = column[m];
336
+ }
337
+ newMatrix.push(intColumn);
338
+ }
339
+ return newMatrix;
340
+ }
341
+ }
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Spectrogram=e():t.Spectrogram=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>r});const s=class{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),()=>this.un(t,e)}once(t,e){const s=this.on(t,e),i=this.on(t,(()=>{s(),i()}));return s}un(t,e){this.listeners[t]&&(e?this.listeners[t].delete(e):delete this.listeners[t])}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}},i=class extends s{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.subscriptions.forEach((t=>t()))}};function a(t,e,s,i){switch(this.bufferSize=t,this.sampleRate=e,this.bandwidth=2/t*(e/2),this.sinTable=new Float32Array(t),this.cosTable=new Float32Array(t),this.windowValues=new Float32Array(t),this.reverseTable=new Uint32Array(t),this.peakBand=0,this.peak=0,s){case"bartlett":for(a=0;a<t;a++)this.windowValues[a]=2/(t-1)*((t-1)/2-Math.abs(a-(t-1)/2));break;case"bartlettHann":for(a=0;a<t;a++)this.windowValues[a]=.62-.48*Math.abs(a/(t-1)-.5)-.38*Math.cos(2*Math.PI*a/(t-1));break;case"blackman":for(i=i||.16,a=0;a<t;a++)this.windowValues[a]=(1-i)/2-.5*Math.cos(2*Math.PI*a/(t-1))+i/2*Math.cos(4*Math.PI*a/(t-1));break;case"cosine":for(a=0;a<t;a++)this.windowValues[a]=Math.cos(Math.PI*a/(t-1)-Math.PI/2);break;case"gauss":for(i=i||.25,a=0;a<t;a++)this.windowValues[a]=Math.pow(Math.E,-.5*Math.pow((a-(t-1)/2)/(i*(t-1)/2),2));break;case"hamming":for(a=0;a<t;a++)this.windowValues[a]=.54-.46*Math.cos(2*Math.PI*a/(t-1));break;case"hann":case void 0:for(a=0;a<t;a++)this.windowValues[a]=.5*(1-Math.cos(2*Math.PI*a/(t-1)));break;case"lanczoz":for(a=0;a<t;a++)this.windowValues[a]=Math.sin(Math.PI*(2*a/(t-1)-1))/(Math.PI*(2*a/(t-1)-1));break;case"rectangular":for(a=0;a<t;a++)this.windowValues[a]=1;break;case"triangular":for(a=0;a<t;a++)this.windowValues[a]=2/t*(t/2-Math.abs(a-(t-1)/2));break;default:throw Error("No such window function '"+s+"'")}for(var a,r=1,n=t>>1;r<t;){for(a=0;a<r;a++)this.reverseTable[a+r]=this.reverseTable[a]+n;r<<=1,n>>=1}for(a=0;a<t;a++)this.sinTable[a]=Math.sin(-Math.PI/a),this.cosTable[a]=Math.cos(-Math.PI/a);this.calculateSpectrum=function(t){var e,s,i,a=this.bufferSize,r=this.cosTable,n=this.sinTable,h=this.reverseTable,l=new Float32Array(a),o=new Float32Array(a),c=2/this.bufferSize,f=Math.sqrt,p=new Float32Array(a/2),u=Math.floor(Math.log(a)/Math.LN2);if(Math.pow(2,u)!==a)throw"Invalid buffer size, must be a power of 2.";if(a!==t.length)throw"Supplied buffer is not the same size as defined FFT. FFT Size: "+a+" Buffer Size: "+t.length;for(var d,w,b,M,g,m,y,v,x=1,S=0;S<a;S++)l[S]=t[h[S]]*this.windowValues[h[S]],o[S]=0;for(;x<a;){d=r[x],w=n[x],b=1,M=0;for(var k=0;k<x;k++){for(S=k;S<a;)m=b*l[g=S+x]-M*o[g],y=b*o[g]+M*l[g],l[g]=l[S]-m,o[g]=o[S]-y,l[S]+=m,o[S]+=y,S+=x<<1;b=(v=b)*d-M*w,M=v*w+M*d}x<<=1}S=0;for(var q=a/2;S<q;S++)(i=c*f((e=l[S])*e+(s=o[S])*s))>this.peak&&(this.peakBand=S,this.peak=i),p[S]=i;return p}}class r extends i{static create(t){return new r(t||{})}constructor(t){if(super(t),this.utils={style:(t,e)=>Object.assign(t.style,e)},this.drawSpectrogram=t=>{isNaN(t[0][0])||(t=[t]);const e=this.spectrCc,s=this.height,i=this.width,a=this.buffer.sampleRate/2,r=this.frequencyMin,n=this.frequencyMax;if(e){for(let h=0;h<t.length;h++){const l=this.resample(t[h]),o=new ImageData(i,s);for(let t=0;t<l.length;t++)for(let e=0;e<l[t].length;e++){const a=this.colorMap[l[t][e]],r=4*((s-e)*i+t);o.data[r]=255*a[0],o.data[r+1]=255*a[1],o.data[r+2]=255*a[2],o.data[r+3]=255*a[3]}createImageBitmap(o).then((t=>{e.drawImage(t,0,s*(1-n/a),i,s*(n-r)/a,0,s*h,i,s)}))}this.emit("ready")}},this.frequenciesDataUrl=t.frequenciesDataUrl,this.container="string"==typeof t.container?document.querySelector(t.container):t.container,t.colorMap){if(t.colorMap.length<256)throw new Error("Colormap must contain 256 elements");for(let e=0;e<t.colorMap.length;e++)if(4!==t.colorMap[e].length)throw new Error("ColorMap entries must contain 4 values");this.colorMap=t.colorMap}else{this.colorMap=[];for(let t=0;t<256;t++){const e=(255-t)/256;this.colorMap.push([e,e,e,1])}}this.fftSamples=t.fftSamples||512,this.height=t.height||this.fftSamples/2,this.noverlap=t.noverlap,this.windowFunc=t.windowFunc,this.alpha=t.alpha,this.channels=1,this.frequencyMin=t.frequencyMin||0,this.frequencyMax=t.frequencyMax||0,this.createWrapper(),this.createCanvas()}onInit(){this.container=this.container||this.wavesurfer.getWrapper(),this.container.appendChild(this.wrapper),this.wavesurfer.options.fillParent&&this.utils.style(this.wrapper,{width:"100%",overflowX:"hidden",overflowY:"hidden"}),this.width=this.wavesurfer.getWrapper().offsetWidth,this.subscriptions.push(this.wavesurfer.on("redraw",(()=>this.render())))}destroy(){this.unAll(),this.wavesurfer.un("ready",this._onReady),this.wavesurfer.un("redraw",this._onRender),this.wavesurfer=null,this.util=null,this.options=null,this.wrapper&&(this.wrapper.remove(),this.wrapper=null)}createWrapper(){if(this.wrapper=document.createElement("div"),this.utils.style(this.wrapper,{display:"block",position:"relative",userSelect:"none",webkitUserSelect:"none",height:this.height*this.channels+"px"}),this.options.labels){const t=document.createElement("canvas");t.setAttribute("part","spec-labels"),t.classList.add("spec-labels"),this.utils.style(t,{position:"absolute",zIndex:9,width:"55px",height:"100%"}),this.wrapper.appendChild(t),this.labelsEl=t}this.wrapper.addEventListener("click",this._onWrapperClick)}_wrapperClickHandler(t){t.preventDefault();const e="offsetX"in t?t.offsetX:t.layerX;this.emit("click",e/this.width||0)}createCanvas(){const t=document.createElement("canvas");this.wrapper.appendChild(t),this.spectrCc=t.getContext("2d"),this.utils.style(t,{position:"absolute",left:0,top:0,width:"100%",height:"100%",zIndex:4}),this.canvas=t}render(){this.canvas.width=this.width,this.canvas.height=this.height,this.frequenciesDataUrl?this.loadFrequenciesData(this.frequenciesDataUrl):this.getFrequencies(this.drawSpectrogram),this.loadLabels(this.options.labelsBackground||"rgba(68,68,68,0.5)","12px","10px","",this.options.labelsColor||"#fff",this.options.labelsHzColor||this.options.labelsColor||"#f7f7f7","center","#specLabels")}getFrequencies(t){const e=this.fftSamples,s=this.wavesurfer.getDecodedData(),i=this.channels;if(this.frequencyMax=this.frequencyMax||s.sampleRate/2,!s)return;this.buffer=s;const r=s.sampleRate,n=[];let h=this.noverlap;if(!h){const t=s.length/this.canvas.width;h=Math.max(0,Math.round(e-t))}const l=new a(e,r,this.windowFunc,this.alpha);for(let t=0;t<i;t++){const i=s.getChannelData(t),a=[];let r=0;for(;r+e<i.length;){const t=i.slice(r,r+e),s=l.calculateSpectrum(t),n=new Uint8Array(e/2);let o;for(o=0;o<e/2;o++)n[o]=Math.max(-255,45*Math.log10(s[o]));a.push(n),r+=e-h}n.push(a)}t(n,this)}loadFrequenciesData(t){return fetch(t).then((t=>t.json())).then(this.drawSpectrogram)}freqType(t){return t>=1e3?(t/1e3).toFixed(1):Math.round(t)}unitType(t){return t>=1e3?"KHz":"Hz"}loadLabels(t,e,s,i,a,r,n,h){t=t||"rgba(68,68,68,0)",e=e||"12px",s=s||"10px",i=i||"Helvetica",a=a||"#fff",r=r||"#fff",n=n||"center",h=h||"#specLabels";const l=this.height||512,o=l/256*5,c=this.frequencyMin,f=(this.frequencyMax-c)/o,p=this.labelsEl.getContext("2d"),u=window.devicePixelRatio;if(this.labelsEl.height=this.height*this.channels*u,this.labelsEl.width=55*u,p.scale(u,u),p)for(let h=0;h<this.channels;h++){let u;for(p.fillStyle=t,p.fillRect(0,h*l,55,(1+h)*l),p.fill(),u=0;u<=o;u++){p.textAlign=n,p.textBaseline="middle";const t=c+f*u,o=this.freqType(t),d=this.unitType(t),w=2,b=16;let M;0==u?(M=(1+h)*l+u-10,p.fillStyle=r,p.font=s+" "+i,p.fillText(d,b+24,M),p.fillStyle=a,p.font=e+" "+i,p.fillText(o,b,M)):(M=(1+h)*l-50*u+w,p.fillStyle=r,p.font=s+" "+i,p.fillText(d,b+24,M),p.fillStyle=a,p.font=e+" "+i,p.fillText(o,b,M))}}}resample(t){const e=this.width,s=[],i=1/t.length,a=1/e;let r;for(r=0;r<e;r++){const e=new Array(t[0].length);let n;for(n=0;n<t.length;n++){const s=n*i,h=s+i,l=r*a,o=l+a,c=h<=l||o<=s?0:Math.min(Math.max(h,l),Math.max(o,s))-Math.max(Math.min(h,l),Math.min(o,s));let f;if(c>0)for(f=0;f<t[0].length;f++)null==e[f]&&(e[f]=0),e[f]+=c/a*t[n][f]}const h=new Uint8Array(t[0].length);let l;for(l=0;l<t[0].length;l++)h[l]=e[l];s.push(h)}return s}}return e.default})()));
@@ -1,29 +1,45 @@
1
+ /**
2
+ * The Timeline plugin adds timestamps and notches under the waveform.
3
+ */
1
4
  import BasePlugin from '../base-plugin.js';
2
- import { WaveSurferPluginParams } from '../index.js';
3
- type TimelinePluginOptions = {
5
+ export type TimelinePluginOptions = {
6
+ /** The height of the timeline in pixels, defaults to 20 */
4
7
  height?: number;
8
+ /** HTML container for the timeline, defaults to wavesufer's container */
5
9
  container?: HTMLElement;
10
+ /** Pass 'beforebegin' to insert the timeline on top of the waveform */
11
+ insertPosition?: InsertPosition;
12
+ /** The duration of the timeline in seconds, defaults to wavesurfer's duration */
13
+ duration?: number;
14
+ /** Interval between ticks in seconds */
6
15
  timeInterval?: number;
16
+ /** Interval between numeric labels */
7
17
  primaryLabelInterval?: number;
18
+ /** Interval between secondary numeric labels */
8
19
  secondaryLabelInterval?: number;
20
+ /** Custom inline style to apply to the container */
21
+ style?: Partial<CSSStyleDeclaration> | string;
9
22
  };
10
23
  declare const defaultOptions: {
11
24
  height: number;
12
25
  };
13
- type TimelinePluginEvents = {
14
- ready: void;
26
+ export type TimelinePluginEvents = {
27
+ ready: [];
15
28
  };
16
29
  declare class TimelinePlugin extends BasePlugin<TimelinePluginEvents, TimelinePluginOptions> {
17
- private wrapper;
30
+ private timelineWrapper;
18
31
  protected options: TimelinePluginOptions & typeof defaultOptions;
19
- constructor(params: WaveSurferPluginParams, options: TimelinePluginOptions);
32
+ constructor(options?: TimelinePluginOptions);
33
+ static create(options?: TimelinePluginOptions): TimelinePlugin;
34
+ /** Called by wavesurfer, don't call manually */
35
+ onInit(): void;
20
36
  /** Unmount */
21
37
  destroy(): void;
22
- private initWrapper;
38
+ private initTimelineWrapper;
23
39
  private formatTime;
24
40
  private defaultTimeInterval;
25
- defaultPrimaryLabelInterval(pxPerSec: number): number;
26
- defaultSecondaryLabelInterval(pxPerSec: number): number;
41
+ private defaultPrimaryLabelInterval;
42
+ private defaultSecondaryLabelInterval;
27
43
  private initTimeline;
28
44
  }
29
45
  export default TimelinePlugin;