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
package/dist/player.js CHANGED
@@ -1,80 +1,97 @@
1
- class Player {
2
- constructor({ media, autoplay }) {
1
+ import EventEmitter from './event-emitter.js';
2
+ class Player extends EventEmitter {
3
+ constructor(options) {
4
+ super();
3
5
  this.isExternalMedia = false;
4
- this.hasPlayedOnce = false;
5
- if (media) {
6
- this.media = media;
6
+ if (options.media) {
7
+ this.media = options.media;
7
8
  this.isExternalMedia = true;
8
9
  }
9
10
  else {
10
11
  this.media = document.createElement('audio');
11
12
  }
12
- // Track the first play() call
13
- const unsubscribe = this.on('play', () => {
14
- this.hasPlayedOnce = true;
15
- unsubscribe();
16
- });
17
13
  // Autoplay
18
- if (autoplay) {
14
+ if (options.autoplay) {
19
15
  this.media.autoplay = true;
20
16
  }
17
+ // Speed
18
+ if (options.playbackRate != null) {
19
+ this.media.playbackRate = options.playbackRate;
20
+ }
21
21
  }
22
- on(event, callback, options) {
22
+ onMediaEvent(event, callback, options) {
23
23
  this.media.addEventListener(event, callback, options);
24
24
  return () => this.media.removeEventListener(event, callback);
25
25
  }
26
+ onceMediaEvent(event, callback) {
27
+ return this.onMediaEvent(event, callback, { once: true });
28
+ }
29
+ revokeSrc() {
30
+ const src = this.media.currentSrc || this.media.src || '';
31
+ if (src.startsWith('blob:')) {
32
+ URL.revokeObjectURL(this.media.currentSrc);
33
+ }
34
+ }
35
+ setSrc(url, blob) {
36
+ const src = this.media.currentSrc || this.media.src || '';
37
+ if (src === url)
38
+ return;
39
+ this.revokeSrc();
40
+ const newSrc = blob instanceof Blob ? URL.createObjectURL(blob) : url;
41
+ this.media.src = newSrc;
42
+ }
26
43
  destroy() {
27
44
  this.media.pause();
45
+ this.revokeSrc();
28
46
  if (!this.isExternalMedia) {
29
47
  this.media.remove();
30
48
  }
31
49
  }
32
- loadUrl(src) {
33
- this.media.src = src;
34
- }
35
- getCurrentTime() {
36
- return this.media.currentTime;
37
- }
50
+ /** Start playing the audio */
38
51
  play() {
39
- this.media.play();
52
+ return this.media.play();
40
53
  }
54
+ /** Pause the audio */
41
55
  pause() {
42
56
  this.media.pause();
43
57
  }
58
+ /** Check if the audio is playing */
44
59
  isPlaying() {
45
60
  return this.media.currentTime > 0 && !this.media.paused && !this.media.ended;
46
61
  }
47
- seekTo(time) {
48
- if (this.media) {
49
- // iOS Safari requires a play() call before seeking
50
- const { hasPlayedOnce } = this;
51
- if (!hasPlayedOnce) {
52
- this.media.play();
53
- }
54
- this.media.currentTime = time;
55
- if (!hasPlayedOnce) {
56
- this.media.pause();
57
- }
58
- }
62
+ /** Jumpt to a specific time in the audio (in seconds) */
63
+ setTime(time) {
64
+ this.media.currentTime = time;
59
65
  }
66
+ /** Get the duration of the audio in seconds */
60
67
  getDuration() {
61
68
  return this.media.duration;
62
69
  }
70
+ /** Get the current audio position in seconds */
71
+ getCurrentTime() {
72
+ return this.media.currentTime;
73
+ }
74
+ /** Get the audio volume */
63
75
  getVolume() {
64
76
  return this.media.volume;
65
77
  }
78
+ /** Set the audio volume */
66
79
  setVolume(volume) {
67
80
  this.media.volume = volume;
68
81
  }
82
+ /** Get the audio muted state */
69
83
  getMuted() {
70
84
  return this.media.muted;
71
85
  }
86
+ /** Mute or unmute the audio */
72
87
  setMuted(muted) {
73
88
  this.media.muted = muted;
74
89
  }
90
+ /** Get the playback speed */
75
91
  getPlaybackRate() {
76
92
  return this.media.playbackRate;
77
93
  }
94
+ /** Set the playback speed, pass an optional false to NOT preserve the pitch */
78
95
  setPlaybackRate(rate, preservePitch) {
79
96
  // preservePitch is true by default in most browsers
80
97
  if (preservePitch != null) {
@@ -82,5 +99,15 @@ class Player {
82
99
  }
83
100
  this.media.playbackRate = rate;
84
101
  }
102
+ /** Get the HTML media element */
103
+ getMediaElement() {
104
+ return this.media;
105
+ }
106
+ /** Set a sink id to change the audio output device */
107
+ setSinkId(sinkId) {
108
+ // See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/setSinkId
109
+ const media = this.media;
110
+ return media.setSinkId(sinkId);
111
+ }
85
112
  }
86
113
  export default Player;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Envelope is a visual UI for controlling the audio volume and add fade-in and fade-out effects.
3
+ */
4
+ import BasePlugin from '../base-plugin.js';
5
+ export type EnvelopePluginOptions = {
6
+ fadeInStart?: number;
7
+ fadeInEnd?: number;
8
+ fadeOutStart?: number;
9
+ fadeOutEnd?: number;
10
+ volume?: number;
11
+ lineWidth?: string;
12
+ lineColor?: string;
13
+ dragPointSize?: number;
14
+ dragPointFill?: string;
15
+ dragPointStroke?: string;
16
+ };
17
+ declare const defaultOptions: {
18
+ fadeInStart: number;
19
+ fadeOutEnd: number;
20
+ fadeInEnd: number;
21
+ fadeOutStart: number;
22
+ lineWidth: number;
23
+ lineColor: string;
24
+ dragPointSize: number;
25
+ dragPointFill: string;
26
+ dragPointStroke: string;
27
+ };
28
+ type Options = EnvelopePluginOptions & typeof defaultOptions;
29
+ export type EnvelopePluginEvents = {
30
+ 'fade-in-change': [time: number];
31
+ 'fade-out-change': [time: number];
32
+ 'volume-change': [volume: number];
33
+ };
34
+ declare class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOptions> {
35
+ protected options: Options;
36
+ private polyline;
37
+ private audioContext;
38
+ private gainNode;
39
+ private volume;
40
+ private isFadingIn;
41
+ private isFadingOut;
42
+ private readonly naturalVolumeExponent;
43
+ constructor(options: EnvelopePluginOptions);
44
+ static create(options: EnvelopePluginOptions): EnvelopePlugin;
45
+ destroy(): void;
46
+ /** Called by wavesurfer, don't call manually */
47
+ onInit(): void;
48
+ private initSvg;
49
+ private renderPolyline;
50
+ private initWebAudio;
51
+ private invertNaturalVolume;
52
+ private naturalVolume;
53
+ private setGainValue;
54
+ private initFadeEffects;
55
+ /** Get the current audio volume */
56
+ getCurrentVolume(): number;
57
+ /**
58
+ * Set the fade-in start time.
59
+ * @param time The time (in seconds) to set the fade-in start time to
60
+ * @param moveFadeInEnd Whether to move the drag point to the new time (default: false)
61
+ */
62
+ setStartTime(time: number, moveFadeInEnd?: boolean): void;
63
+ /** Set the fade-in end time.
64
+ * @param time The time (in seconds) to set the fade-in end time to
65
+ * @param moveFadeOutStart Whether to move the drag point to the new time (default: false)
66
+ */
67
+ setEndTime(time: number, moveFadeOutStart?: boolean): void;
68
+ /** Set the volume of the audio */
69
+ setVolume(volume: number): void;
70
+ }
71
+ export default EnvelopePlugin;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Envelope is a visual UI for controlling the audio volume and add fade-in and fade-out effects.
3
+ */
4
+ import BasePlugin from '../base-plugin.js';
5
+ import { makeDraggable } from '../draggable.js';
6
+ import EventEmitter from '../event-emitter.js';
7
+ const defaultOptions = {
8
+ fadeInStart: 0,
9
+ fadeOutEnd: 0,
10
+ fadeInEnd: 0,
11
+ fadeOutStart: 0,
12
+ lineWidth: 4,
13
+ lineColor: 'rgba(0, 0, 255, 0.5)',
14
+ dragPointSize: 10,
15
+ dragPointFill: 'rgba(255, 255, 255, 0.8)',
16
+ dragPointStroke: 'rgba(255, 255, 255, 0.8)',
17
+ };
18
+ class Polyline extends EventEmitter {
19
+ constructor(options, wrapper) {
20
+ super();
21
+ this.top = 0;
22
+ // An padding to make the envelope fit into the SVG
23
+ this.padding = options.dragPointSize / 2 + 1;
24
+ // SVG element
25
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
26
+ svg.setAttribute('width', '100%');
27
+ svg.setAttribute('height', '100%');
28
+ svg.setAttribute('viewBox', '0 0 0 0');
29
+ svg.setAttribute('preserveAspectRatio', 'none');
30
+ svg.setAttribute('style', 'position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none;');
31
+ svg.setAttribute('part', 'envelope');
32
+ this.svg = svg;
33
+ // A polyline representing the envelope
34
+ const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
35
+ polyline.setAttribute('points', '0,0 0,0 0,0 0,0');
36
+ polyline.setAttribute('stroke', options.lineColor);
37
+ polyline.setAttribute('stroke-width', options.lineWidth);
38
+ polyline.setAttribute('fill', 'none');
39
+ polyline.setAttribute('style', 'pointer-events: none;');
40
+ polyline.setAttribute('part', 'polyline');
41
+ svg.appendChild(polyline);
42
+ // Draggable top line
43
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
44
+ line.setAttribute('stroke', 'transparent');
45
+ line.setAttribute('stroke-width', (options.lineWidth * 3).toString());
46
+ line.setAttribute('style', 'cursor: ns-resize; pointer-events: all;');
47
+ line.setAttribute('part', 'line');
48
+ svg.appendChild(line);
49
+ [0, 1].forEach(() => {
50
+ const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
51
+ circle.setAttribute('r', (options.dragPointSize / 2).toString());
52
+ circle.setAttribute('fill', options.dragPointFill);
53
+ circle.setAttribute('stroke', options.dragPointStroke || options.dragPointFill);
54
+ circle.setAttribute('stroke-width', '2');
55
+ circle.setAttribute('style', 'cursor: ew-resize; pointer-events: all;');
56
+ circle.setAttribute('part', 'circle');
57
+ svg.appendChild(circle);
58
+ });
59
+ wrapper.appendChild(svg);
60
+ // Init dtagging
61
+ {
62
+ // On top line drag
63
+ const onDragY = (dy) => {
64
+ const newTop = this.top + dy;
65
+ const { height } = svg.viewBox.baseVal;
66
+ if (newTop < -0.5 || newTop > height)
67
+ return;
68
+ const relativeY = Math.min(1, Math.max(0, (height - newTop) / height));
69
+ this.emit('line-move', relativeY);
70
+ };
71
+ // On points drag
72
+ const onDragX = (index, dx) => {
73
+ const point = polyline.points.getItem(index);
74
+ const newX = point.x + dx;
75
+ const { width } = svg.viewBox.baseVal;
76
+ this.emit('point-move', index, newX / width);
77
+ };
78
+ // Draggable top line of the polyline
79
+ this.makeDraggable(line, (_, y) => onDragY(y));
80
+ // Make each point draggable
81
+ const draggables = this.svg.querySelectorAll('circle');
82
+ Array.from(draggables).forEach((draggable, index) => {
83
+ this.makeDraggable(draggable, (x) => onDragX(index + 1, x));
84
+ });
85
+ }
86
+ }
87
+ makeDraggable(draggable, onDrag) {
88
+ makeDraggable(draggable, onDrag);
89
+ }
90
+ update({ x1, x2, x3, x4, y }) {
91
+ const width = this.svg.clientWidth;
92
+ const height = this.svg.clientHeight;
93
+ this.top = height - y * height;
94
+ const paddedTop = Math.max(this.padding, Math.min(this.top, height - this.padding));
95
+ this.svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
96
+ const polyline = this.svg.querySelector('polyline');
97
+ const { points } = polyline;
98
+ points.getItem(0).x = x1 * width;
99
+ points.getItem(0).y = height;
100
+ points.getItem(1).x = x2 * width;
101
+ points.getItem(1).y = paddedTop;
102
+ points.getItem(2).x = x3 * width;
103
+ points.getItem(2).y = paddedTop;
104
+ points.getItem(3).x = x4 * width;
105
+ points.getItem(3).y = height;
106
+ const line = this.svg.querySelector('line');
107
+ line.setAttribute('x1', points.getItem(1).x.toString());
108
+ line.setAttribute('x2', points.getItem(2).x.toString());
109
+ line.setAttribute('y1', paddedTop.toString());
110
+ line.setAttribute('y2', paddedTop.toString());
111
+ const circles = this.svg.querySelectorAll('circle');
112
+ Array.from(circles).forEach((circle, i) => {
113
+ const point = points.getItem(i + 1);
114
+ circle.setAttribute('cx', point.x.toString());
115
+ circle.setAttribute('cy', point.y.toString());
116
+ });
117
+ }
118
+ destroy() {
119
+ this.svg.remove();
120
+ }
121
+ }
122
+ class EnvelopePlugin extends BasePlugin {
123
+ constructor(options) {
124
+ super(options);
125
+ this.polyline = null;
126
+ this.audioContext = null;
127
+ this.gainNode = null;
128
+ this.volume = 1;
129
+ this.isFadingIn = false;
130
+ this.isFadingOut = false;
131
+ // Adjust the exponent to change the curve of the volume control
132
+ this.naturalVolumeExponent = 1.5;
133
+ this.options = Object.assign({}, defaultOptions, options);
134
+ this.options.lineColor = this.options.lineColor || defaultOptions.lineColor;
135
+ this.options.dragPointFill = this.options.dragPointFill || defaultOptions.dragPointFill;
136
+ this.options.dragPointStroke = this.options.dragPointStroke || defaultOptions.dragPointStroke;
137
+ this.volume = this.options.volume ?? 1;
138
+ }
139
+ static create(options) {
140
+ return new EnvelopePlugin(options);
141
+ }
142
+ destroy() {
143
+ this.polyline?.destroy();
144
+ super.destroy();
145
+ }
146
+ /** Called by wavesurfer, don't call manually */
147
+ onInit() {
148
+ if (!this.wavesurfer) {
149
+ throw Error('WaveSurfer is not initialized');
150
+ }
151
+ this.initWebAudio();
152
+ this.initSvg();
153
+ this.initFadeEffects();
154
+ this.subscriptions.push(this.wavesurfer.on('redraw', () => {
155
+ const duration = this.wavesurfer?.getDuration();
156
+ if (!duration)
157
+ return;
158
+ this.options.fadeInStart = this.options.fadeInStart || 0;
159
+ this.options.fadeOutEnd = this.options.fadeOutEnd || duration;
160
+ this.options.fadeInEnd = this.options.fadeInEnd || this.options.fadeInStart;
161
+ this.options.fadeOutStart = this.options.fadeOutStart || this.options.fadeOutEnd;
162
+ this.renderPolyline();
163
+ }));
164
+ }
165
+ initSvg() {
166
+ if (!this.wavesurfer)
167
+ return;
168
+ const wrapper = this.wavesurfer.getWrapper();
169
+ this.polyline = new Polyline(this.options, wrapper);
170
+ this.subscriptions.push(this.polyline.on('line-move', (relativeY) => {
171
+ this.setVolume(this.naturalVolume(relativeY));
172
+ }), this.polyline.on('point-move', (index, relativeX) => {
173
+ const duration = this.wavesurfer?.getDuration() || 0;
174
+ const newTime = relativeX * duration;
175
+ // Fade-in end point
176
+ if (index === 1) {
177
+ if (newTime < this.options.fadeInStart || newTime > this.options.fadeOutStart)
178
+ return;
179
+ this.options.fadeInEnd = newTime;
180
+ this.emit('fade-in-change', newTime);
181
+ }
182
+ else if (index === 2) {
183
+ // Fade-out start point
184
+ if (newTime > this.options.fadeOutEnd || newTime < this.options.fadeInEnd)
185
+ return;
186
+ this.options.fadeOutStart = newTime;
187
+ this.emit('fade-out-change', newTime);
188
+ }
189
+ this.renderPolyline();
190
+ }));
191
+ }
192
+ renderPolyline() {
193
+ if (!this.polyline || !this.wavesurfer)
194
+ return;
195
+ const duration = this.wavesurfer.getDuration();
196
+ if (!duration)
197
+ return;
198
+ this.polyline.update({
199
+ x1: this.options.fadeInStart / duration,
200
+ x2: this.options.fadeInEnd / duration,
201
+ x3: this.options.fadeOutStart / duration,
202
+ x4: this.options.fadeOutEnd / duration,
203
+ y: this.invertNaturalVolume(this.volume),
204
+ });
205
+ }
206
+ initWebAudio() {
207
+ const audio = this.wavesurfer?.getMediaElement();
208
+ if (!audio)
209
+ return null;
210
+ this.volume = this.options.volume ?? audio.volume;
211
+ // Create an AudioContext
212
+ const audioContext = new window.AudioContext();
213
+ // Create a GainNode for controlling the volume
214
+ this.gainNode = audioContext.createGain();
215
+ this.setGainValue();
216
+ // Create a MediaElementAudioSourceNode using the audio element
217
+ const source = audioContext.createMediaElementSource(audio);
218
+ // Connect the source to the GainNode, and the GainNode to the destination (speakers)
219
+ source.connect(this.gainNode);
220
+ this.gainNode.connect(audioContext.destination);
221
+ this.audioContext = audioContext;
222
+ }
223
+ invertNaturalVolume(value) {
224
+ const minValue = 0.0001;
225
+ const maxValue = 1;
226
+ const interpolatedValue = Math.pow((value - minValue) / (maxValue - minValue), 1 / this.naturalVolumeExponent);
227
+ return interpolatedValue;
228
+ }
229
+ naturalVolume(value) {
230
+ const minValue = 0.0001;
231
+ const maxValue = 1;
232
+ const interpolatedValue = minValue + (maxValue - minValue) * Math.pow(value, this.naturalVolumeExponent);
233
+ return interpolatedValue;
234
+ }
235
+ setGainValue() {
236
+ if (this.gainNode) {
237
+ this.gainNode.gain.value = this.volume;
238
+ }
239
+ }
240
+ initFadeEffects() {
241
+ if (!this.audioContext || !this.wavesurfer)
242
+ return;
243
+ const unsub = this.wavesurfer.on('timeupdate', (currentTime) => {
244
+ if (!this.audioContext || !this.gainNode)
245
+ return;
246
+ if (!this.wavesurfer?.isPlaying())
247
+ return;
248
+ if (this.audioContext.state === 'suspended') {
249
+ this.audioContext.resume();
250
+ }
251
+ // Fade in
252
+ if (!this.isFadingIn && currentTime >= this.options.fadeInStart && currentTime <= this.options.fadeInEnd) {
253
+ this.isFadingIn = true;
254
+ // Set the initial gain (volume) to 0 (silent)
255
+ this.gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
256
+ // Set the target gain (volume) to 1 (full volume) over N seconds
257
+ this.gainNode.gain.linearRampToValueAtTime(this.volume, this.audioContext.currentTime + (this.options.fadeInEnd - currentTime));
258
+ return;
259
+ }
260
+ // Fade out
261
+ if (!this.isFadingOut && currentTime >= this.options.fadeOutStart && currentTime <= this.options.fadeOutEnd) {
262
+ this.isFadingOut = true;
263
+ /**
264
+ * Set the gain at this point in time to the current volume, otherwise
265
+ * the audio will start fading out from the fade-in point.
266
+ */
267
+ this.gainNode.gain.setValueAtTime(this.volume, this.audioContext.currentTime);
268
+ // Set the target gain (volume) to 0 (silent) over N seconds
269
+ this.gainNode.gain.linearRampToValueAtTime(0, this.audioContext.currentTime + (this.options.fadeOutEnd - currentTime));
270
+ return;
271
+ }
272
+ // Reset fade in/out
273
+ let cancelRamp = false;
274
+ if (this.isFadingIn && (currentTime < this.options.fadeInStart || currentTime > this.options.fadeInEnd)) {
275
+ this.isFadingIn = false;
276
+ cancelRamp = true;
277
+ }
278
+ if (this.isFadingOut && (currentTime < this.options.fadeOutStart || currentTime >= this.options.fadeOutEnd)) {
279
+ this.isFadingOut = false;
280
+ cancelRamp = true;
281
+ }
282
+ if (cancelRamp) {
283
+ this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime);
284
+ this.setGainValue();
285
+ }
286
+ });
287
+ this.subscriptions.push(unsub);
288
+ }
289
+ /** Get the current audio volume */
290
+ getCurrentVolume() {
291
+ return this.gainNode ? this.gainNode.gain.value : this.volume;
292
+ }
293
+ /**
294
+ * Set the fade-in start time.
295
+ * @param time The time (in seconds) to set the fade-in start time to
296
+ * @param moveFadeInEnd Whether to move the drag point to the new time (default: false)
297
+ */
298
+ setStartTime(time, moveFadeInEnd = false) {
299
+ if (moveFadeInEnd) {
300
+ const rampLength = this.options.fadeInEnd - this.options.fadeInStart;
301
+ this.options.fadeInEnd = time + rampLength;
302
+ }
303
+ this.options.fadeInStart = time;
304
+ this.renderPolyline();
305
+ }
306
+ /** Set the fade-in end time.
307
+ * @param time The time (in seconds) to set the fade-in end time to
308
+ * @param moveFadeOutStart Whether to move the drag point to the new time (default: false)
309
+ */
310
+ setEndTime(time, moveFadeOutStart = false) {
311
+ if (moveFadeOutStart) {
312
+ const rampLength = this.options.fadeOutEnd - this.options.fadeOutStart;
313
+ this.options.fadeOutStart = time - rampLength;
314
+ }
315
+ this.options.fadeOutEnd = time;
316
+ this.renderPolyline();
317
+ }
318
+ /** Set the volume of the audio */
319
+ setVolume(volume) {
320
+ this.volume = volume;
321
+ this.setGainValue();
322
+ this.renderPolyline();
323
+ this.emit('volume-change', volume);
324
+ }
325
+ }
326
+ export default EnvelopePlugin;
@@ -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.Envelope=e():t.Envelope=e()}(WaveSurfer,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>a});const i=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 i=this.on(t,e),n=this.on(t,(()=>{i(),n()}));return i}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)))}},n=class extends i{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}init(t){this.wavesurfer=t,this.onInit()}destroy(){this.subscriptions.forEach((t=>t()))}},s={fadeInStart:0,fadeOutEnd:0,fadeInEnd:0,fadeOutStart:0,lineWidth:4,lineColor:"rgba(0, 0, 255, 0.5)",dragPointSize:10,dragPointFill:"rgba(255, 255, 255, 0.8)",dragPointStroke:"rgba(255, 255, 255, 0.8)"};class o extends i{constructor(t,e){super(),this.top=0,this.padding=t.dragPointSize/2+1;const i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("viewBox","0 0 0 0"),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("style","position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none;"),i.setAttribute("part","envelope"),this.svg=i;const n=document.createElementNS("http://www.w3.org/2000/svg","polyline");n.setAttribute("points","0,0 0,0 0,0 0,0"),n.setAttribute("stroke",t.lineColor),n.setAttribute("stroke-width",t.lineWidth),n.setAttribute("fill","none"),n.setAttribute("style","pointer-events: none;"),n.setAttribute("part","polyline"),i.appendChild(n);const s=document.createElementNS("http://www.w3.org/2000/svg","line");s.setAttribute("stroke","transparent"),s.setAttribute("stroke-width",(3*t.lineWidth).toString()),s.setAttribute("style","cursor: ns-resize; pointer-events: all;"),s.setAttribute("part","line"),i.appendChild(s),[0,1].forEach((()=>{const e=document.createElementNS("http://www.w3.org/2000/svg","circle");e.setAttribute("r",(t.dragPointSize/2).toString()),e.setAttribute("fill",t.dragPointFill),e.setAttribute("stroke",t.dragPointStroke||t.dragPointFill),e.setAttribute("stroke-width","2"),e.setAttribute("style","cursor: ew-resize; pointer-events: all;"),e.setAttribute("part","circle"),i.appendChild(e)})),e.appendChild(i);{const t=t=>{const e=this.top+t,{height:n}=i.viewBox.baseVal;if(e<-.5||e>n)return;const s=Math.min(1,Math.max(0,(n-e)/n));this.emit("line-move",s)},e=(t,e)=>{const s=n.points.getItem(t).x+e,{width:o}=i.viewBox.baseVal;this.emit("point-move",t,s/o)};this.makeDraggable(s,((e,i)=>t(i)));const o=this.svg.querySelectorAll("circle");Array.from(o).forEach(((t,i)=>{this.makeDraggable(t,(t=>e(i+1,t)))}))}}makeDraggable(t,e){!function(t,e,i,n,s=5){let o=()=>{};if(!t)return o;t.addEventListener("pointerdown",(r=>{r.preventDefault(),r.stopPropagation();let a=r.clientX,u=r.clientY,h=!1;const d=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY;if(h||Math.abs(o-a)>=s||Math.abs(r-u)>=s){h||(h=!0,i?.(a,u));const{left:n,top:s}=t.getBoundingClientRect();e(o-a,r-u,o-n,r-s),a=o,u=r}},l=t=>{h&&(t.preventDefault(),t.stopPropagation())},p=()=>{h&&n?.(),o()};o=()=>{document.removeEventListener("pointermove",d),document.removeEventListener("pointerup",p),document.removeEventListener("pointerleave",p),setTimeout((()=>{document.removeEventListener("click",l,!0)}),10)},document.addEventListener("pointermove",d),document.addEventListener("pointerup",p),document.addEventListener("pointerleave",p),document.addEventListener("click",l,!0)}))}(t,e)}update({x1:t,x2:e,x3:i,x4:n,y:s}){const o=this.svg.clientWidth,r=this.svg.clientHeight;this.top=r-s*r;const a=Math.max(this.padding,Math.min(this.top,r-this.padding));this.svg.setAttribute("viewBox",`0 0 ${o} ${r}`);const u=this.svg.querySelector("polyline"),{points:h}=u;h.getItem(0).x=t*o,h.getItem(0).y=r,h.getItem(1).x=e*o,h.getItem(1).y=a,h.getItem(2).x=i*o,h.getItem(2).y=a,h.getItem(3).x=n*o,h.getItem(3).y=r;const d=this.svg.querySelector("line");d.setAttribute("x1",h.getItem(1).x.toString()),d.setAttribute("x2",h.getItem(2).x.toString()),d.setAttribute("y1",a.toString()),d.setAttribute("y2",a.toString());const l=this.svg.querySelectorAll("circle");Array.from(l).forEach(((t,e)=>{const i=h.getItem(e+1);t.setAttribute("cx",i.x.toString()),t.setAttribute("cy",i.y.toString())}))}destroy(){this.svg.remove()}}class r extends n{constructor(t){super(t),this.polyline=null,this.audioContext=null,this.gainNode=null,this.volume=1,this.isFadingIn=!1,this.isFadingOut=!1,this.naturalVolumeExponent=1.5,this.options=Object.assign({},s,t),this.options.lineColor=this.options.lineColor||s.lineColor,this.options.dragPointFill=this.options.dragPointFill||s.dragPointFill,this.options.dragPointStroke=this.options.dragPointStroke||s.dragPointStroke,this.volume=this.options.volume??1}static create(t){return new r(t)}destroy(){this.polyline?.destroy(),super.destroy()}onInit(){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.initWebAudio(),this.initSvg(),this.initFadeEffects(),this.subscriptions.push(this.wavesurfer.on("redraw",(()=>{const t=this.wavesurfer?.getDuration();t&&(this.options.fadeInStart=this.options.fadeInStart||0,this.options.fadeOutEnd=this.options.fadeOutEnd||t,this.options.fadeInEnd=this.options.fadeInEnd||this.options.fadeInStart,this.options.fadeOutStart=this.options.fadeOutStart||this.options.fadeOutEnd,this.renderPolyline())})))}initSvg(){if(!this.wavesurfer)return;const t=this.wavesurfer.getWrapper();this.polyline=new o(this.options,t),this.subscriptions.push(this.polyline.on("line-move",(t=>{this.setVolume(this.naturalVolume(t))})),this.polyline.on("point-move",((t,e)=>{const i=e*(this.wavesurfer?.getDuration()||0);if(1===t){if(i<this.options.fadeInStart||i>this.options.fadeOutStart)return;this.options.fadeInEnd=i,this.emit("fade-in-change",i)}else if(2===t){if(i>this.options.fadeOutEnd||i<this.options.fadeInEnd)return;this.options.fadeOutStart=i,this.emit("fade-out-change",i)}this.renderPolyline()})))}renderPolyline(){if(!this.polyline||!this.wavesurfer)return;const t=this.wavesurfer.getDuration();t&&this.polyline.update({x1:this.options.fadeInStart/t,x2:this.options.fadeInEnd/t,x3:this.options.fadeOutStart/t,x4:this.options.fadeOutEnd/t,y:this.invertNaturalVolume(this.volume)})}initWebAudio(){const t=this.wavesurfer?.getMediaElement();if(!t)return null;this.volume=this.options.volume??t.volume;const e=new window.AudioContext;this.gainNode=e.createGain(),this.setGainValue(),e.createMediaElementSource(t).connect(this.gainNode),this.gainNode.connect(e.destination),this.audioContext=e}invertNaturalVolume(t){return Math.pow((t-1e-4)/.9999,1/this.naturalVolumeExponent)}naturalVolume(t){return 1e-4+.9999*Math.pow(t,this.naturalVolumeExponent)}setGainValue(){this.gainNode&&(this.gainNode.gain.value=this.volume)}initFadeEffects(){if(!this.audioContext||!this.wavesurfer)return;const t=this.wavesurfer.on("timeupdate",(t=>{if(!this.audioContext||!this.gainNode)return;if(!this.wavesurfer?.isPlaying())return;if("suspended"===this.audioContext.state&&this.audioContext.resume(),!this.isFadingIn&&t>=this.options.fadeInStart&&t<=this.options.fadeInEnd)return this.isFadingIn=!0,this.gainNode.gain.setValueAtTime(0,this.audioContext.currentTime),void this.gainNode.gain.linearRampToValueAtTime(this.volume,this.audioContext.currentTime+(this.options.fadeInEnd-t));if(!this.isFadingOut&&t>=this.options.fadeOutStart&&t<=this.options.fadeOutEnd)return this.isFadingOut=!0,this.gainNode.gain.setValueAtTime(this.volume,this.audioContext.currentTime),void this.gainNode.gain.linearRampToValueAtTime(0,this.audioContext.currentTime+(this.options.fadeOutEnd-t));let e=!1;this.isFadingIn&&(t<this.options.fadeInStart||t>this.options.fadeInEnd)&&(this.isFadingIn=!1,e=!0),this.isFadingOut&&(t<this.options.fadeOutStart||t>=this.options.fadeOutEnd)&&(this.isFadingOut=!1,e=!0),e&&(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.setGainValue())}));this.subscriptions.push(t)}getCurrentVolume(){return this.gainNode?this.gainNode.gain.value:this.volume}setStartTime(t,e=!1){if(e){const e=this.options.fadeInEnd-this.options.fadeInStart;this.options.fadeInEnd=t+e}this.options.fadeInStart=t,this.renderPolyline()}setEndTime(t,e=!1){if(e){const e=this.options.fadeOutEnd-this.options.fadeOutStart;this.options.fadeOutStart=t-e}this.options.fadeOutEnd=t,this.renderPolyline()}setVolume(t){this.volume=t,this.setGainValue(),this.renderPolyline(),this.emit("volume-change",t)}}const a=r;return e.default})()));
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Minimap is a tiny copy of the main waveform serving as a navigation tool.
3
+ */
4
+ import BasePlugin from '../base-plugin.js';
5
+ import { type WaveSurferOptions } from '../wavesurfer.js';
6
+ export type MinimapPluginOptions = {
7
+ overlayColor?: string;
8
+ insertPosition?: InsertPosition;
9
+ } & WaveSurferOptions;
10
+ declare const defaultOptions: {
11
+ height: number;
12
+ overlayColor: string;
13
+ insertPosition: string;
14
+ };
15
+ export type MinimapPluginEvents = {
16
+ ready: [];
17
+ interaction: [];
18
+ };
19
+ declare class MinimapPlugin extends BasePlugin<MinimapPluginEvents, MinimapPluginOptions> {
20
+ protected options: MinimapPluginOptions & typeof defaultOptions;
21
+ private minimapWrapper;
22
+ private miniWavesurfer;
23
+ private overlay;
24
+ private container;
25
+ constructor(options: MinimapPluginOptions);
26
+ static create(options: MinimapPluginOptions): MinimapPlugin;
27
+ /** Called by wavesurfer, don't call manually */
28
+ onInit(): void;
29
+ private initMinimapWrapper;
30
+ private initOverlay;
31
+ private initMinimap;
32
+ private getOverlayWidth;
33
+ private onRedraw;
34
+ private onScroll;
35
+ private initWaveSurferEvents;
36
+ /** Unmount */
37
+ destroy(): void;
38
+ }
39
+ export default MinimapPlugin;