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

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 (58) hide show
  1. package/README.md +90 -18
  2. package/dist/base-plugin.d.ts +6 -4
  3. package/dist/base-plugin.js +9 -3
  4. package/dist/decoder.d.ts +8 -7
  5. package/dist/decoder.js +43 -38
  6. package/dist/event-emitter.d.ts +16 -10
  7. package/dist/event-emitter.js +38 -16
  8. package/dist/fetcher.d.ts +4 -3
  9. package/dist/fetcher.js +5 -15
  10. package/dist/player.d.ts +31 -11
  11. package/dist/player.js +58 -31
  12. package/dist/plugins/envelope.d.ts +71 -0
  13. package/dist/plugins/envelope.js +347 -0
  14. package/dist/plugins/envelope.min.cjs +1 -0
  15. package/dist/plugins/envelope.min.js +1 -0
  16. package/dist/plugins/minimap.d.ts +39 -0
  17. package/dist/plugins/minimap.js +114 -0
  18. package/dist/plugins/minimap.min.cjs +1 -0
  19. package/dist/plugins/minimap.min.js +1 -0
  20. package/dist/plugins/multitrack.d.ts +85 -12
  21. package/dist/plugins/multitrack.js +331 -84
  22. package/dist/plugins/multitrack.min.cjs +1 -0
  23. package/dist/plugins/multitrack.min.js +1 -0
  24. package/dist/plugins/record.d.ts +26 -0
  25. package/dist/plugins/record.js +126 -0
  26. package/dist/plugins/record.min.cjs +1 -0
  27. package/dist/plugins/record.min.js +1 -0
  28. package/dist/plugins/regions.d.ts +83 -43
  29. package/dist/plugins/regions.js +362 -192
  30. package/dist/plugins/regions.min.cjs +1 -0
  31. package/dist/plugins/regions.min.js +1 -0
  32. package/dist/plugins/spectrogram.d.ts +69 -0
  33. package/dist/plugins/spectrogram.js +340 -0
  34. package/dist/plugins/spectrogram.min.cjs +1 -0
  35. package/dist/plugins/spectrogram.min.js +1 -0
  36. package/dist/plugins/timeline.d.ts +25 -9
  37. package/dist/plugins/timeline.js +65 -24
  38. package/dist/plugins/timeline.min.cjs +1 -0
  39. package/dist/plugins/timeline.min.js +1 -0
  40. package/dist/renderer.d.ts +29 -13
  41. package/dist/renderer.js +280 -161
  42. package/dist/timer.d.ts +1 -1
  43. package/dist/wavesurfer.d.ts +151 -0
  44. package/dist/wavesurfer.js +241 -0
  45. package/dist/wavesurfer.min.cjs +1 -0
  46. package/dist/wavesurfer.min.js +1 -1
  47. package/package.json +55 -28
  48. package/dist/index.d.ts +0 -117
  49. package/dist/index.js +0 -227
  50. package/dist/player-webaudio.d.ts +0 -8
  51. package/dist/player-webaudio.js +0 -32
  52. package/dist/plugins/xmultitrack.d.ts +0 -44
  53. package/dist/plugins/xmultitrack.js +0 -260
  54. package/dist/react/useWavesurfer.d.ts +0 -5
  55. package/dist/react/useWavesurfer.js +0 -20
  56. package/dist/wavesurfer.Multitrack.min.js +0 -1
  57. package/dist/wavesurfer.Regions.min.js +0 -1
  58. package/dist/wavesurfer.Timeline.min.js +0 -1
package/README.md CHANGED
@@ -1,48 +1,120 @@
1
1
  # <img src="https://user-images.githubusercontent.com/381895/226091100-f5567a28-7736-4d37-8f84-e08f297b7e1a.png" alt="logo" height="60" valign="middle" /> wavesurfer.ts
2
2
 
3
- An experimental rewrite of [wavesufer.js](https://github.com/wavesurfer-js/wavesurfer.js) to play around with new ideas.
3
+ ![npm](https://img.shields.io/npm/v/wavesurfer.js/beta)
4
+
5
+ A rewrite of [wavesufer.js](https://github.com/wavesurfer-js/wavesurfer.js) in TypeScript with better performance.
4
6
 
5
7
  <img alt="screenshot" src="https://user-images.githubusercontent.com/381895/225539680-fc724acd-8657-458e-a558-ff1c6758ba30.png" width="800" />
6
8
 
7
9
  Try it out:
8
10
  ```
9
- npm install --save wavesurfer.js@alpha
11
+ npm install --save wavesurfer.js@beta
12
+ ```
13
+
14
+ Alternatively, import from a CDN or a local file as an ES6 module:
15
+
16
+ ```
17
+ import WaveSurfer from 'https://unpkg.com/wavesurfer.js@beta'
18
+ ```
19
+
20
+ Or, as a UMD script tag which exposes `WaveSurfer` as a global variable:
21
+ ```
22
+ <script src="https://unpkg.com/wavesurfer.js@beta/dist/wavesurfer.min.js"></script>
23
+ ```
24
+
25
+ To import a plugin, e.g. the Timeline plugin:
26
+ ```
27
+ import Timeline from 'https://unpkg.com/wavesurfer.js@beta/dist/plugins/timeline.js'
10
28
  ```
11
29
 
12
- ## Goals
30
+ TypeScript types are included in the package, so there's no need to install `@types/wavesurfer.js`.
13
31
 
14
- * TypeScript API
15
- * Better architecture
16
- * Minimize the available options and provide sensible defaults
17
- * Improve the decoding and rendering performance
32
+ ## Why upgrade to wavesurfer.ts?
18
33
 
19
- ## Non-goals
34
+ wavesurfer.js v7 (aka wavesurfer.ts) brings several improvements:
20
35
 
21
- Keeping backwards compatibility with earlier versions of wavesurfer.js.
36
+ * Typed API for better development experience
37
+ * Enhanced decoding and rendering performance
38
+ * New and improved plugins
22
39
 
23
- ## Architecture
40
+ ## Plugins
41
+ The "official" plugins have been completely rewritten and enhanced:
24
42
 
25
- Principles:
26
- * Modular and event-driven
27
- * Flexible (e.g. allow custom media elements and user-defined Web Audio graphs)
28
- * Extensible with plugins
43
+ * [Regions](https://wavesurfer.pages.dev/examples/#regions.js) – now also replaces the old Markers plugin
44
+ * [Timeline](https://wavesurfer.pages.dev/examples/#timeline.js) – displays notches and time labels below the waveform
45
+ * [Minimap](https://wavesurfer.pages.dev/examples/#minimap.js) a small waveform that serves as a scrollbar for the main waveform
46
+ * [Envelope](https://wavesurfer.pages.dev/examples/#envelope.js) a graphical interface to add fade-in and -out effects and control volume
47
+ * [Record](https://wavesurfer.pages.dev/examples/#record.js) – records audio from the microphone and renders a waveform
48
+ * [Spectrogram](https://wavesurfer.pages.dev/examples/#spectrogram.js) – visualization of an audio frequency spectrum
49
+
50
+ ## CSS styling
51
+
52
+ wavesurfer.js v7 is rendered into a Shadow DOM tree. This isolates its CSS from the rest of the web page.
53
+ However, it's still possible to style various wavesurfer.js elements via CSS using the `::part()` pseudo-selector.
54
+ For example:
55
+
56
+ ```css
57
+ #waveform ::part(cursor):before {
58
+ content: '🏄';
59
+ }
60
+ #waveform ::part(region) {
61
+ font-family: fantasy;
62
+ }
63
+ ```
64
+
65
+ You can see which elements you can style in the DOM inspector – they will have a `part` attribute.
66
+
67
+ <img width="466" alt="DOM inspector screenshot" src="https://github.com/katspaugh/wavesurfer.ts/assets/381895/fcfb4e4d-9572-4931-811f-9615b7e3aa85">
68
+
69
+ See [this example](https://wavesurfer.pages.dev/examples/#styling.js) for play around with styling.
70
+
71
+ ## Documentation
72
+ See the documentation on wavesurfer.js [methods](https://wavesurfer-ts.pages.dev/docs/classes/wavesurfer.WaveSurfer), [options](https://wavesurfer-ts.pages.dev/docs/types/wavesurfer.WaveSurferOptions) and [events](https://wavesurfer-ts.pages.dev/docs/types/wavesurfer.WaveSurferEvents) on our website.
73
+
74
+ ## Migrating from v6 and lower
75
+
76
+ Most options, events, and methods are similar to those in previous versions.
77
+
78
+ ### Notable differences
79
+ * The `backend` option is removed – HTML5 audio (or video) is the only playback mechanism. However, you can still connect wavesurfer to Web Audio via `MediaElementSourceNode`. See this [example](https://wavesurfer.pages.dev/examples/#webaudio.js).
80
+ * The Markers plugin is removed – use the Regions plugin with `startTime` equal to `endTime`.
81
+ * No Microphone plugn – superseded by the new Record plugin with more features.
82
+ * No Cursor and Playhead plugins yet – to be done.
83
+
84
+ ### Removed methods
85
+ * `getFilters`, `setFilter` – as there's no Web Audio "backend"
86
+ * `drawBuffer` – to redraw the waveform, use `setOptions` instead and pass new rendering options
87
+ * `cancelAjax` – ajax is replaced by `fetch`
88
+ * `loadBlob` – use `URL.createObjectURL()` to convert a blob to a URL and call `load(url)` instead
89
+ * `skipForward`, `skipBackward`, `setPlayEnd` – can be implemented using `setTime(time)`
90
+ * `exportPCM` is renamed to `getDecodedData` and doesn't take any params
91
+ * `toggleMute` is now called `setMuted(true | false)`
92
+ * `setHeight`, `setWaveColor`, `setCursorColor`, etc. – use `setOptions` with the corresponding params instead. E.g., `wavesurfer.setOptions({ height: 300, waveColor: '#abc' })`
93
+
94
+ See the complete [documentation of the new API](https://wavesurfer-ts.pages.dev/docs/modules/wavesurfer).
29
95
 
30
96
  ## Development
31
97
 
32
- Install dev dependencies:
98
+ To get started with development, follow these steps:
99
+
100
+ 1. Install dev dependencies:
33
101
 
34
102
  ```
35
103
  yarn
36
104
  ```
37
105
 
38
- Start the TypeScript compiler in watch mode and an HTTP server:
106
+ 2. Start the TypeScript compiler in watch mode and launch an HTTP server:
39
107
 
40
108
  ```
41
109
  yarn start
42
110
  ```
43
111
 
44
- This will open http://localhost:9090/tutorial in your browser with live reload.
112
+ This command will open http://localhost:9090/tutorial in your browser with live reload, allowing you to see the changes as you develop.
45
113
 
46
114
  ## Feedback
47
115
 
48
- Your feedback is very welcome here: https://github.com/wavesurfer-js/wavesurfer.js/discussions/2684
116
+ We appreciate your feedback and contributions! Join the conversation and share your thoughts here: https://github.com/wavesurfer-js/wavesurfer.js/discussions/2684
117
+
118
+ If you encounter any issues or have suggestions for improvements, please don't hesitate to open an issue or submit a pull request on the GitHub repository.
119
+
120
+ We hope you enjoy using wavesurfer.ts and look forward to hearing about your experiences with the library!
@@ -1,11 +1,13 @@
1
1
  import EventEmitter, { type GeneralEventTypes } from './event-emitter.js';
2
- import type { WaveSurfer, WaveSurferPluginParams } from './index.js';
2
+ import type WaveSurfer from './wavesurfer.js';
3
+ export type GenericPlugin = BasePlugin<GeneralEventTypes, unknown>;
3
4
  export declare class BasePlugin<EventTypes extends GeneralEventTypes, Options> extends EventEmitter<EventTypes> {
4
- protected wavesurfer: WaveSurfer;
5
- protected container: HTMLElement;
5
+ protected wavesurfer?: WaveSurfer;
6
6
  protected subscriptions: (() => void)[];
7
7
  protected options: Options;
8
- constructor(params: WaveSurferPluginParams, options: Options);
8
+ constructor(options: Options);
9
+ onInit(): void;
10
+ init(wavesurfer: WaveSurfer): void;
9
11
  destroy(): void;
10
12
  }
11
13
  export default BasePlugin;
@@ -1,12 +1,18 @@
1
1
  import EventEmitter from './event-emitter.js';
2
2
  export class BasePlugin extends EventEmitter {
3
- constructor(params, options) {
3
+ constructor(options) {
4
4
  super();
5
5
  this.subscriptions = [];
6
- this.wavesurfer = params.wavesurfer;
7
- this.container = params.container;
8
6
  this.options = options;
9
7
  }
8
+ onInit() {
9
+ // Overridden in plugin definition
10
+ return;
11
+ }
12
+ init(wavesurfer) {
13
+ this.wavesurfer = wavesurfer;
14
+ this.onInit();
15
+ }
10
16
  destroy() {
11
17
  this.subscriptions.forEach((unsubscribe) => unsubscribe());
12
18
  }
package/dist/decoder.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- declare class Decoder {
2
- audioCtx: AudioContext | null;
3
- private initAudioContext;
4
- constructor();
5
- decode(audioData: ArrayBuffer): Promise<AudioBuffer>;
6
- destroy(): void;
7
- }
1
+ /** Decode an array buffer into an audio buffer */
2
+ declare function decode(audioData: ArrayBuffer, sampleRate: number): Promise<AudioBuffer>;
3
+ /** Create an audio buffer from pre-decoded audio data */
4
+ declare function createBuffer(channelData: Float32Array[] | Array<number[]>, duration: number): AudioBuffer;
5
+ declare const Decoder: {
6
+ decode: typeof decode;
7
+ createBuffer: typeof createBuffer;
8
+ };
8
9
  export default Decoder;
package/dist/decoder.js CHANGED
@@ -1,43 +1,48 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- class Decoder {
11
- initAudioContext(sampleRate) {
12
- this.audioCtx = new AudioContext({
13
- latencyHint: 'playback',
14
- sampleRate,
15
- });
16
- }
17
- constructor() {
18
- this.audioCtx = null;
19
- // Minimum sample rate supported by Web Audio API
20
- const DEFAULT_SAMPLE_RATE = 3000; // Chrome, Safari
21
- const FALLBACK_SAMPLE_RATE = 8000; // Firefox
22
- try {
23
- this.initAudioContext(DEFAULT_SAMPLE_RATE);
24
- }
25
- catch (e) {
26
- this.initAudioContext(FALLBACK_SAMPLE_RATE);
1
+ /** Decode an array buffer into an audio buffer */
2
+ async function decode(audioData, sampleRate) {
3
+ const audioCtx = new AudioContext({ sampleRate });
4
+ const decode = audioCtx.decodeAudioData(audioData);
5
+ decode.finally(() => audioCtx.close());
6
+ return decode;
7
+ }
8
+ /** Normalize peaks to -1..1 */
9
+ function normalize(channelData) {
10
+ const firstChannel = channelData[0];
11
+ if (firstChannel.some((n) => n > 1 || n < -1)) {
12
+ const length = firstChannel.length;
13
+ let max = 0;
14
+ for (let i = 0; i < length; i++) {
15
+ const absN = Math.abs(firstChannel[i]);
16
+ if (absN > max)
17
+ max = absN;
27
18
  }
28
- }
29
- decode(audioData) {
30
- return __awaiter(this, void 0, void 0, function* () {
31
- if (!this.audioCtx) {
32
- throw new Error('AudioContext is not initialized');
19
+ for (const channel of channelData) {
20
+ for (let i = 0; i < length; i++) {
21
+ channel[i] /= max;
33
22
  }
34
- return this.audioCtx.decodeAudioData(audioData);
35
- });
36
- }
37
- destroy() {
38
- var _a;
39
- (_a = this.audioCtx) === null || _a === void 0 ? void 0 : _a.close();
40
- this.audioCtx = null;
23
+ }
41
24
  }
25
+ return channelData;
42
26
  }
27
+ /** Create an audio buffer from pre-decoded audio data */
28
+ function createBuffer(channelData, duration) {
29
+ // If a single array of numbers is passed, make it an array of arrays
30
+ if (typeof channelData[0] === 'number')
31
+ channelData = [channelData];
32
+ // Normalize to -1..1
33
+ normalize(channelData);
34
+ return {
35
+ duration,
36
+ length: channelData[0].length,
37
+ sampleRate: channelData[0].length / duration,
38
+ numberOfChannels: channelData.length,
39
+ getChannelData: (i) => channelData?.[i],
40
+ copyFromChannel: AudioBuffer.prototype.copyFromChannel,
41
+ copyToChannel: AudioBuffer.prototype.copyToChannel,
42
+ };
43
+ }
44
+ const Decoder = {
45
+ decode,
46
+ createBuffer,
47
+ };
43
48
  export default Decoder;
@@ -1,13 +1,19 @@
1
- export interface GeneralEventTypes {
2
- [eventType: string]: unknown;
3
- }
1
+ export type GeneralEventTypes = {
2
+ [EventName: string]: any[];
3
+ };
4
+ type EventListener<EventTypes extends GeneralEventTypes, EventName extends keyof EventTypes> = (...args: EventTypes[EventName]) => void;
5
+ /** A simple event emitter that can be used to listen to and emit events. */
4
6
  declare class EventEmitter<EventTypes extends GeneralEventTypes> {
5
- private eventTarget;
6
- constructor();
7
- protected emit<T extends keyof EventTypes>(eventType: T, detail?: EventTypes[T]): void;
8
- /** Subscribe to an event and return a function to unsubscribe */
9
- on<T extends keyof EventTypes>(eventType: T, callback: (detail: EventTypes[T]) => void, once?: boolean): () => void;
10
- /** Subscribe to an event once and return a function to unsubscribe */
11
- once<T extends keyof EventTypes>(eventType: T, callback: (detail: EventTypes[T]) => void): () => void;
7
+ private listeners;
8
+ /** Subscribe to an event. Returns an unsubscribe function. */
9
+ on<EventName extends keyof EventTypes>(eventName: EventName, listener: EventListener<EventTypes, EventName>): () => void;
10
+ /** Subscribe to an event only once */
11
+ once<EventName extends keyof EventTypes>(eventName: EventName, listener: EventListener<EventTypes, EventName>): () => void;
12
+ /** Unsubscribe from an event */
13
+ un<EventName extends keyof EventTypes>(eventName: EventName, listener: EventListener<EventTypes, EventName>): void;
14
+ /** Clear all events */
15
+ unAll(): void;
16
+ /** Emit an event */
17
+ protected emit<EventName extends keyof EventTypes>(eventName: EventName, ...args: EventTypes[EventName]): void;
12
18
  }
13
19
  export default EventEmitter;
@@ -1,25 +1,47 @@
1
+ /** A simple event emitter that can be used to listen to and emit events. */
1
2
  class EventEmitter {
2
3
  constructor() {
3
- this.eventTarget = new EventTarget();
4
+ this.listeners = {};
4
5
  }
5
- emit(eventType, detail) {
6
- const e = new CustomEvent(String(eventType), { detail });
7
- this.eventTarget.dispatchEvent(e);
6
+ /** Subscribe to an event. Returns an unsubscribe function. */
7
+ on(eventName, listener) {
8
+ if (!this.listeners[eventName]) {
9
+ this.listeners[eventName] = new Set();
10
+ }
11
+ this.listeners[eventName].add(listener);
12
+ return () => this.un(eventName, listener);
8
13
  }
9
- /** Subscribe to an event and return a function to unsubscribe */
10
- on(eventType, callback, once) {
11
- const handler = (e) => {
12
- if (e instanceof CustomEvent) {
13
- callback(e.detail);
14
+ /** Subscribe to an event only once */
15
+ once(eventName, listener) {
16
+ // The actual subscription
17
+ const unsubscribe = this.on(eventName, listener);
18
+ // Another subscription that will unsubscribe the actual subscription and itself after the first event
19
+ const unsubscribeOnce = this.on(eventName, () => {
20
+ unsubscribe();
21
+ unsubscribeOnce();
22
+ });
23
+ return unsubscribe;
24
+ }
25
+ /** Unsubscribe from an event */
26
+ un(eventName, listener) {
27
+ if (this.listeners[eventName]) {
28
+ if (listener) {
29
+ this.listeners[eventName].delete(listener);
30
+ }
31
+ else {
32
+ delete this.listeners[eventName];
14
33
  }
15
- };
16
- const eventName = String(eventType);
17
- this.eventTarget.addEventListener(eventName, handler, { once });
18
- return () => this.eventTarget.removeEventListener(eventName, handler);
34
+ }
35
+ }
36
+ /** Clear all events */
37
+ unAll() {
38
+ this.listeners = {};
19
39
  }
20
- /** Subscribe to an event once and return a function to unsubscribe */
21
- once(eventType, callback) {
22
- return this.on(eventType, callback, true);
40
+ /** Emit an event */
41
+ emit(eventName, ...args) {
42
+ if (this.listeners[eventName]) {
43
+ this.listeners[eventName].forEach((listener) => listener(...args));
44
+ }
23
45
  }
24
46
  }
25
47
  export default EventEmitter;
package/dist/fetcher.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- declare class Fetcher {
2
- load(url: string): Promise<ArrayBuffer>;
3
- }
1
+ declare function fetchArrayBuffer(url: string): Promise<ArrayBuffer>;
2
+ declare const Fetcher: {
3
+ fetchArrayBuffer: typeof fetchArrayBuffer;
4
+ };
4
5
  export default Fetcher;
package/dist/fetcher.js CHANGED
@@ -1,17 +1,7 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- class Fetcher {
11
- load(url) {
12
- return __awaiter(this, void 0, void 0, function* () {
13
- return fetch(url).then((response) => response.arrayBuffer());
14
- });
15
- }
1
+ async function fetchArrayBuffer(url) {
2
+ return fetch(url).then((response) => response.arrayBuffer());
16
3
  }
4
+ const Fetcher = {
5
+ fetchArrayBuffer,
6
+ };
17
7
  export default Fetcher;
package/dist/player.d.ts CHANGED
@@ -1,25 +1,45 @@
1
- declare class Player {
1
+ import EventEmitter, { type GeneralEventTypes } from './event-emitter.js';
2
+ type PlayerOptions = {
3
+ media?: HTMLMediaElement;
4
+ autoplay?: boolean;
5
+ playbackRate?: number;
6
+ };
7
+ declare class Player<T extends GeneralEventTypes> extends EventEmitter<T> {
2
8
  protected media: HTMLMediaElement;
3
9
  private isExternalMedia;
4
- private hasPlayedOnce;
5
- constructor({ media, autoplay }: {
6
- media?: HTMLMediaElement;
7
- autoplay?: boolean;
8
- });
9
- on(event: keyof HTMLMediaElementEventMap, callback: () => void, options?: AddEventListenerOptions): () => void;
10
+ constructor(options: PlayerOptions);
11
+ protected onMediaEvent(event: keyof HTMLMediaElementEventMap, callback: () => void, options?: AddEventListenerOptions): () => void;
12
+ protected onceMediaEvent(event: keyof HTMLMediaElementEventMap, callback: () => void): () => void;
13
+ private revokeSrc;
14
+ protected setSrc(url: string, arrayBuffer?: ArrayBuffer): void;
10
15
  destroy(): void;
11
- loadUrl(src: string): void;
12
- getCurrentTime(): number;
13
- play(): void;
16
+ /** Start playing the audio */
17
+ play(): Promise<void>;
18
+ /** Pause the audio */
14
19
  pause(): void;
20
+ /** Check if the audio is playing */
15
21
  isPlaying(): boolean;
16
- seekTo(time: number): void;
22
+ /** Jumpt to a specific time in the audio (in seconds) */
23
+ setTime(time: number): void;
24
+ /** Get the duration of the audio in seconds */
17
25
  getDuration(): number;
26
+ /** Get the current audio position in seconds */
27
+ getCurrentTime(): number;
28
+ /** Get the audio volume */
18
29
  getVolume(): number;
30
+ /** Set the audio volume */
19
31
  setVolume(volume: number): void;
32
+ /** Get the audio muted state */
20
33
  getMuted(): boolean;
34
+ /** Mute or unmute the audio */
21
35
  setMuted(muted: boolean): void;
36
+ /** Get the playback speed */
22
37
  getPlaybackRate(): number;
38
+ /** Set the playback speed, pass an optional false to NOT preserve the pitch */
23
39
  setPlaybackRate(rate: number, preservePitch?: boolean): void;
40
+ /** Get the HTML media element */
41
+ getMediaElement(): HTMLMediaElement;
42
+ /** Set a sink id to change the audio output device */
43
+ setSinkId(sinkId: string): Promise<void>;
24
44
  }
25
45
  export default Player;
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, arrayBuffer) {
36
+ const src = this.media.currentSrc || this.media.src || '';
37
+ if (src === url)
38
+ return;
39
+ this.revokeSrc();
40
+ const newSrc = arrayBuffer ? URL.createObjectURL(new Blob([arrayBuffer], { type: 'audio/wav' })) : 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;