waveframe 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.css +3 -0
- package/dist/index.css.map +1 -0
- package/dist/index.d.cts +562 -0
- package/dist/index.d.ts +562 -2
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/package.json +8 -8
- package/dist/src/App.d.ts +0 -2
- package/dist/src/__tests__/WaveframePlayer.test.d.ts +0 -1
- package/dist/src/atoms/CodeBlock.d.ts +0 -9
- package/dist/src/components/WaveframePlayer.d.ts +0 -83
- package/dist/src/core/PeakAnalyzer.d.ts +0 -41
- package/dist/src/core/PlayerCore.d.ts +0 -92
- package/dist/src/core/WaveframeEngine.d.ts +0 -122
- package/dist/src/hooks/usePersistentSettings.d.ts +0 -1
- package/dist/src/hooks/useResampledPeaks.d.ts +0 -1
- package/dist/src/hooks/useResizeObserver.d.ts +0 -1
- package/dist/src/hooks/useWaveframe.d.ts +0 -51
- package/dist/src/hooks/useWaveframeStore.d.ts +0 -27
- package/dist/src/index.d.ts +0 -7
- package/dist/src/main.d.ts +0 -0
- package/dist/src/molecules/ArtworkOverlay.d.ts +0 -20
- package/dist/src/organisms/SettingsPanel.d.ts +0 -29
- package/dist/src/organisms/Waveform.d.ts +0 -15
- package/dist/src/types/index.d.ts +0 -75
- package/dist/src/utils/audio.d.ts +0 -33
- package/dist/src/utils/index.d.ts +0 -13
- package/dist/waveframe.cjs +0 -7
- package/dist/waveframe.css +0 -3
- package/dist/waveframe.es.js +0 -603
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,562 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import React$1 from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Defines the core color palette for the Waveframe component.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```tsx
|
|
8
|
+
* const darkTheme: WaveframeTheme = {
|
|
9
|
+
* bg: '#111827',
|
|
10
|
+
* primary: '#ec4899',
|
|
11
|
+
* text: '#f9fafb',
|
|
12
|
+
* border: '#1f2937'
|
|
13
|
+
* };
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
interface WaveframeTheme {
|
|
17
|
+
/** The main background color of the player */
|
|
18
|
+
bg: string;
|
|
19
|
+
/** The primary accent color (used for play button and progress) */
|
|
20
|
+
primary: string;
|
|
21
|
+
/** The color of the text elements (title, artist, time) */
|
|
22
|
+
text: string;
|
|
23
|
+
/** The color of borders and dividers */
|
|
24
|
+
border: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Metadata associated with an audio track.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```tsx
|
|
31
|
+
* const track: TrackInfo = {
|
|
32
|
+
* title: 'Electronic Sunset',
|
|
33
|
+
* artist: 'Digital Nomad',
|
|
34
|
+
* artwork: 'https://example.com/art.jpg', // or a Blob object
|
|
35
|
+
* audioUrl: 'https://example.com/audio.mp3'
|
|
36
|
+
* };
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
interface TrackInfo {
|
|
40
|
+
/** The title of the track */
|
|
41
|
+
title: string;
|
|
42
|
+
/** The artist of the track */
|
|
43
|
+
artist: string;
|
|
44
|
+
/** The artwork source (URL string or Blob/File object) */
|
|
45
|
+
artwork: string | Blob;
|
|
46
|
+
/** The URL to the actual audio file */
|
|
47
|
+
audioUrl: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Defines the resolution of the waveform.
|
|
51
|
+
* - `number`: A fixed number of bars to render.
|
|
52
|
+
* - `'auto'`: Compute the number of bars dynamically based on the container width.
|
|
53
|
+
*/
|
|
54
|
+
type Resolution = number | 'auto';
|
|
55
|
+
/**
|
|
56
|
+
* Configuration options for how the waveform is rendered visually.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```tsx
|
|
60
|
+
* const config: WaveformConfig = {
|
|
61
|
+
* resolution: 'auto',
|
|
62
|
+
* barWidth: 2,
|
|
63
|
+
* barGap: 1,
|
|
64
|
+
* height: 100
|
|
65
|
+
* };
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
interface WaveformConfig {
|
|
69
|
+
/** The number of bars to render, or 'auto' to compute based on container width */
|
|
70
|
+
resolution: Resolution;
|
|
71
|
+
/** The width of each individual bar in pixels */
|
|
72
|
+
barWidth: number;
|
|
73
|
+
/** The spacing between each bar in pixels */
|
|
74
|
+
barGap: number;
|
|
75
|
+
/** The total height of the waveform in pixels */
|
|
76
|
+
height: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Represents the low-level playback state of the audio element.
|
|
81
|
+
*/
|
|
82
|
+
type PlayerState = {
|
|
83
|
+
/** Whether the audio is currently playing */
|
|
84
|
+
isPlaying: boolean;
|
|
85
|
+
/** The current playback time in seconds */
|
|
86
|
+
currentTime: number;
|
|
87
|
+
/** The total duration of the track in seconds */
|
|
88
|
+
duration: number;
|
|
89
|
+
/** The current volume level (0 to 1) */
|
|
90
|
+
volume: number;
|
|
91
|
+
/** Whether the audio is currently muted */
|
|
92
|
+
muted: boolean;
|
|
93
|
+
/** Any error reported by the audio element */
|
|
94
|
+
error: string | null;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* A callback function that receives the latest PlayerState.
|
|
98
|
+
*/
|
|
99
|
+
type PlayerListener = (state: PlayerState) => void;
|
|
100
|
+
/**
|
|
101
|
+
* The internal core class responsible for managing the HTMLAudioElement.
|
|
102
|
+
*
|
|
103
|
+
* It handles raw playback logic, volume control, and synchronizes the
|
|
104
|
+
* internal `PlayerState` with DOM events from the underlying `Audio` instance.
|
|
105
|
+
*/
|
|
106
|
+
declare class PlayerCore {
|
|
107
|
+
private audio;
|
|
108
|
+
private listeners;
|
|
109
|
+
private _state;
|
|
110
|
+
/**
|
|
111
|
+
* Initializes a new PlayerCore instance and sets up event listeners on a new Audio object.
|
|
112
|
+
*/
|
|
113
|
+
constructor();
|
|
114
|
+
/**
|
|
115
|
+
* Subscribes to various HTMLMediaElement events to keep the internal state in sync.
|
|
116
|
+
*/
|
|
117
|
+
private initListeners;
|
|
118
|
+
/**
|
|
119
|
+
* Updates the internal state and notifies subscribers.
|
|
120
|
+
*/
|
|
121
|
+
private updateState;
|
|
122
|
+
/**
|
|
123
|
+
* Triggers all registered listener callbacks.
|
|
124
|
+
*/
|
|
125
|
+
private notify;
|
|
126
|
+
/**
|
|
127
|
+
* Registers a listener for state updates.
|
|
128
|
+
* @param listener The callback function.
|
|
129
|
+
* @returns An unsubscribe function.
|
|
130
|
+
*/
|
|
131
|
+
subscribe(listener: PlayerListener): () => boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Returns the current playback state.
|
|
134
|
+
*/
|
|
135
|
+
get state(): PlayerState;
|
|
136
|
+
/**
|
|
137
|
+
* Updates the source URL of the underlying audio element.
|
|
138
|
+
* @param url The audio source URL.
|
|
139
|
+
*/
|
|
140
|
+
setSource(url: string): void;
|
|
141
|
+
/**
|
|
142
|
+
* Starts playback. Returns a promise that resolves when playback begins.
|
|
143
|
+
*/
|
|
144
|
+
play(): Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* Pauses playback.
|
|
147
|
+
*/
|
|
148
|
+
pause(): void;
|
|
149
|
+
/**
|
|
150
|
+
* Toggles between play and pause states.
|
|
151
|
+
*/
|
|
152
|
+
togglePlay(): Promise<void>;
|
|
153
|
+
/**
|
|
154
|
+
* Seeks to a specific time.
|
|
155
|
+
* @param time Time in seconds.
|
|
156
|
+
*/
|
|
157
|
+
seek(time: number): void;
|
|
158
|
+
/**
|
|
159
|
+
* Sets the volume level.
|
|
160
|
+
* @param volume Level from 0 to 1.
|
|
161
|
+
*/
|
|
162
|
+
setVolume(volume: number): void;
|
|
163
|
+
/**
|
|
164
|
+
* Mutes or unmutes the audio element.
|
|
165
|
+
* @param muted Mute status.
|
|
166
|
+
*/
|
|
167
|
+
setMuted(muted: boolean): void;
|
|
168
|
+
/**
|
|
169
|
+
* Cleans up the audio element and removes all listeners.
|
|
170
|
+
*/
|
|
171
|
+
dispose(): void;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Represents the complete state of the Waveframe engine, combining playback and analysis.
|
|
176
|
+
*/
|
|
177
|
+
type EngineState = PlayerState & {
|
|
178
|
+
/** The current set of generated or provided waveform peaks (0-1 range) */
|
|
179
|
+
peaks: number[];
|
|
180
|
+
/** Whether an audio analysis process is currently in progress */
|
|
181
|
+
isAnalyzing: boolean;
|
|
182
|
+
/** Any error message encountered during playback or analysis */
|
|
183
|
+
error: string | null;
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* A callback function that receives the latest EngineState.
|
|
187
|
+
*/
|
|
188
|
+
type EngineListener = (state: EngineState) => void;
|
|
189
|
+
/**
|
|
190
|
+
* The orchestrator class for Waveframe.
|
|
191
|
+
*
|
|
192
|
+
* It manages the lifecycle of audio playback and waveform analysis, providing a unified
|
|
193
|
+
* store-like interface that can be easily consumed by React or other frameworks.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```typescript
|
|
197
|
+
* const engine = new WaveframeEngine();
|
|
198
|
+
*
|
|
199
|
+
* // Load from URL (automatic analysis if peaks omitted)
|
|
200
|
+
* engine.load('https://example.com/audio.mp3');
|
|
201
|
+
*
|
|
202
|
+
* // Load from Blob with pre-computed peaks
|
|
203
|
+
* engine.load(myBlob, [0.1, 0.5, 0.8]);
|
|
204
|
+
*
|
|
205
|
+
* // Subscription
|
|
206
|
+
* const unsubscribe = engine.subscribe((state) => {
|
|
207
|
+
* console.log('Current time:', state.currentTime);
|
|
208
|
+
* });
|
|
209
|
+
* ```
|
|
210
|
+
*/
|
|
211
|
+
declare class WaveframeEngine {
|
|
212
|
+
private player;
|
|
213
|
+
private analyzer;
|
|
214
|
+
private listeners;
|
|
215
|
+
private _state;
|
|
216
|
+
private _media;
|
|
217
|
+
private _objectUrl;
|
|
218
|
+
/**
|
|
219
|
+
* Creates a new instance of the WaveframeEngine.
|
|
220
|
+
* Initializes internal PlayerCore and PeakAnalyzer.
|
|
221
|
+
*/
|
|
222
|
+
constructor();
|
|
223
|
+
/**
|
|
224
|
+
* Internal method to update the state and notify all subscribers.
|
|
225
|
+
*/
|
|
226
|
+
private updateState;
|
|
227
|
+
/**
|
|
228
|
+
* Notifies all registered listeners of a state change.
|
|
229
|
+
*/
|
|
230
|
+
private notify;
|
|
231
|
+
/**
|
|
232
|
+
* Registers a listener to be called whenever the engine state changes.
|
|
233
|
+
* @param listener The callback function.
|
|
234
|
+
* @returns An unsubscribe function.
|
|
235
|
+
*/
|
|
236
|
+
subscribe(listener: EngineListener): () => boolean;
|
|
237
|
+
/**
|
|
238
|
+
* Returns a snapshot of the current engine state.
|
|
239
|
+
* Useful for `useSyncExternalStore`.
|
|
240
|
+
*/
|
|
241
|
+
getSnapshot(): EngineState;
|
|
242
|
+
/**
|
|
243
|
+
* Revokes any existing Object URLs to prevent memory leaks.
|
|
244
|
+
*/
|
|
245
|
+
private revokeOldSource;
|
|
246
|
+
/**
|
|
247
|
+
* Loads media (URL or Blob) into the player.
|
|
248
|
+
*
|
|
249
|
+
* If a string is passed, it's treated as a URL and used directly for playback.
|
|
250
|
+
* If a Blob is passed, an Object URL is created for playback.
|
|
251
|
+
*
|
|
252
|
+
* If `peaks` are not provided, it automatically triggers an analysis.
|
|
253
|
+
*
|
|
254
|
+
* @param media The audio source (URL string or Blob/File object).
|
|
255
|
+
* @param peaks Optional pre-generated peaks for the waveform.
|
|
256
|
+
*/
|
|
257
|
+
load(media: string | Blob, peaks?: number[]): void;
|
|
258
|
+
/**
|
|
259
|
+
* Analyzes the current media to generate waveform peaks.
|
|
260
|
+
* @param samples The number of peaks to generate. Defaults to 512.
|
|
261
|
+
*/
|
|
262
|
+
analyze(samples?: number): Promise<void>;
|
|
263
|
+
/**
|
|
264
|
+
* Toggles playback between playing and paused.
|
|
265
|
+
*/
|
|
266
|
+
togglePlay(): void;
|
|
267
|
+
/**
|
|
268
|
+
* Starts audio playback.
|
|
269
|
+
*/
|
|
270
|
+
play(): void;
|
|
271
|
+
/**
|
|
272
|
+
* Pauses audio playback.
|
|
273
|
+
*/
|
|
274
|
+
pause(): void;
|
|
275
|
+
/**
|
|
276
|
+
* Seeks to a specific position in the track.
|
|
277
|
+
* @param percentage The seek position as a decimal (0 to 1).
|
|
278
|
+
*/
|
|
279
|
+
seek(percentage: number): void;
|
|
280
|
+
/**
|
|
281
|
+
* Sets the playback volume.
|
|
282
|
+
* @param volume The volume level (0 to 1).
|
|
283
|
+
*/
|
|
284
|
+
setVolume(volume: number): void;
|
|
285
|
+
/**
|
|
286
|
+
* Mutes or unmutes the audio.
|
|
287
|
+
* @param muted Whether the audio should be muted.
|
|
288
|
+
*/
|
|
289
|
+
setMuted(muted: boolean): void;
|
|
290
|
+
/**
|
|
291
|
+
* Disposes of the engine, pausing playback and clearing all listeners and resources.
|
|
292
|
+
*/
|
|
293
|
+
dispose(): void;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Props for the WaveframePlayer component
|
|
298
|
+
*/
|
|
299
|
+
interface WaveframePlayerProps {
|
|
300
|
+
/**
|
|
301
|
+
* The audio source to play. Can be a URL string or a Blob/File object.
|
|
302
|
+
*/
|
|
303
|
+
media?: string | Blob;
|
|
304
|
+
/**
|
|
305
|
+
* Optional pre-generated peaks for the waveform (0-1 range).
|
|
306
|
+
* If omitted or empty, the player will automatically analyze the media.
|
|
307
|
+
*/
|
|
308
|
+
peaks?: number[];
|
|
309
|
+
/**
|
|
310
|
+
* The artwork source to display. Can be a URL string or a Blob/File object.
|
|
311
|
+
*/
|
|
312
|
+
artwork?: string | Blob;
|
|
313
|
+
/**
|
|
314
|
+
* The title of the track
|
|
315
|
+
*/
|
|
316
|
+
title?: string;
|
|
317
|
+
/**
|
|
318
|
+
* The artist of the track
|
|
319
|
+
*/
|
|
320
|
+
artist?: string;
|
|
321
|
+
/**
|
|
322
|
+
* The base color of the waveform bars
|
|
323
|
+
* @default "#e5e7eb" (light) or "#374151" (dark)
|
|
324
|
+
*/
|
|
325
|
+
waveColor?: string;
|
|
326
|
+
/**
|
|
327
|
+
* The color of the played progress part of the waveform
|
|
328
|
+
* @default theme.primary or "#3b82f6"
|
|
329
|
+
*/
|
|
330
|
+
progressColor?: string;
|
|
331
|
+
/**
|
|
332
|
+
* The height of the waveform in pixels
|
|
333
|
+
* @default 80
|
|
334
|
+
*/
|
|
335
|
+
height?: number;
|
|
336
|
+
/**
|
|
337
|
+
* Additional CSS classes for the container
|
|
338
|
+
*/
|
|
339
|
+
className?: string;
|
|
340
|
+
/**
|
|
341
|
+
* Inline styles for the container
|
|
342
|
+
*/
|
|
343
|
+
style?: React$1.CSSProperties;
|
|
344
|
+
/**
|
|
345
|
+
* The number of bars to render. Use 'auto' to fit the container width.
|
|
346
|
+
* @default "auto"
|
|
347
|
+
*/
|
|
348
|
+
resolution?: number | 'auto';
|
|
349
|
+
/**
|
|
350
|
+
* The width of each bar in pixels (if resolution is 'auto')
|
|
351
|
+
* @default 2
|
|
352
|
+
*/
|
|
353
|
+
barWidth?: number;
|
|
354
|
+
/**
|
|
355
|
+
* The gap between bars in pixels (if resolution is 'auto')
|
|
356
|
+
* @default 1
|
|
357
|
+
*/
|
|
358
|
+
barGap?: number;
|
|
359
|
+
/**
|
|
360
|
+
* Custom theme configuration
|
|
361
|
+
*/
|
|
362
|
+
theme?: WaveframeTheme;
|
|
363
|
+
/**
|
|
364
|
+
* Optional WaveframeEngine instance for external control.
|
|
365
|
+
* If provided, the player will sync with this engine instead of creating its own.
|
|
366
|
+
*/
|
|
367
|
+
engine?: WaveframeEngine;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The standard "all-in-one" Waveframe player component.
|
|
371
|
+
*
|
|
372
|
+
* This component features a SoundCloud-inspired layout with a prominent
|
|
373
|
+
* play/pause button positioned next to the track metadata.
|
|
374
|
+
*/
|
|
375
|
+
declare const WaveframePlayer: React$1.FC<WaveframePlayerProps>;
|
|
376
|
+
|
|
377
|
+
interface WaveformProps {
|
|
378
|
+
peaks: number[];
|
|
379
|
+
currentTime: number;
|
|
380
|
+
duration: number;
|
|
381
|
+
waveColor: string;
|
|
382
|
+
progressColor: string;
|
|
383
|
+
height: number;
|
|
384
|
+
onSeek: (percentage: number) => void;
|
|
385
|
+
resolution?: number | 'auto';
|
|
386
|
+
barWidth?: number;
|
|
387
|
+
barGap?: number;
|
|
388
|
+
}
|
|
389
|
+
declare const Waveform: React$1.FC<WaveformProps>;
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* A specialized class for decoding audio data and generating waveform peaks.
|
|
393
|
+
*
|
|
394
|
+
* It leverages the Web Audio API (`AudioContext`) to process audio buffers
|
|
395
|
+
* and extract amplitude data for visualization.
|
|
396
|
+
*/
|
|
397
|
+
declare class PeakAnalyzer {
|
|
398
|
+
private audioCtx;
|
|
399
|
+
/**
|
|
400
|
+
* Initializes the analyzer. AudioContext creation is deferred to the first use
|
|
401
|
+
* to comply with browser autoplay and resource management policies.
|
|
402
|
+
*/
|
|
403
|
+
constructor();
|
|
404
|
+
/**
|
|
405
|
+
* Lazily creates or returns the existing AudioContext.
|
|
406
|
+
*/
|
|
407
|
+
private getContext;
|
|
408
|
+
/**
|
|
409
|
+
* Processes media (URL or Blob) and generates a set of normalized peaks.
|
|
410
|
+
*
|
|
411
|
+
* @param media The URL string or Blob object to analyze.
|
|
412
|
+
* @param samples The number of peaks (bars) to generate. Defaults to 512.
|
|
413
|
+
* @returns A promise resolving to an array of normalized peak values (0 to 1).
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* ```typescript
|
|
417
|
+
* const analyzer = new PeakAnalyzer();
|
|
418
|
+
*
|
|
419
|
+
* // Analyze from URL
|
|
420
|
+
* const peaksFromUrl = await analyzer.generatePeaks('https://example.com/audio.mp3');
|
|
421
|
+
*
|
|
422
|
+
* // Analyze from Blob
|
|
423
|
+
* const peaksFromBlob = await analyzer.generatePeaks(myAudioBlob);
|
|
424
|
+
* ```
|
|
425
|
+
*/
|
|
426
|
+
generatePeaks(media: string | Blob, samples?: number): Promise<number[]>;
|
|
427
|
+
/**
|
|
428
|
+
* Closes the AudioContext and releases system audio resources.
|
|
429
|
+
*/
|
|
430
|
+
dispose(): void;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Configuration options for the `useWaveframe` hook.
|
|
435
|
+
*/
|
|
436
|
+
interface UseWaveframeOptions {
|
|
437
|
+
/** Optional pre-computed peaks to skip automatic analysis */
|
|
438
|
+
peaks?: number[];
|
|
439
|
+
/** Optional external engine instance for shared playback across components */
|
|
440
|
+
engine?: WaveframeEngine;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* A headless hook that provides full control over the Waveframe engine.
|
|
444
|
+
*
|
|
445
|
+
* It manages the engine's lifecycle, loads the provided media, and returns
|
|
446
|
+
* the current state along with playback controls.
|
|
447
|
+
*
|
|
448
|
+
* @param media The audio source (URL string or Blob/File object).
|
|
449
|
+
* @param options Additional configuration and an optional external engine.
|
|
450
|
+
*
|
|
451
|
+
* @example
|
|
452
|
+
* ```tsx
|
|
453
|
+
* const { state, togglePlay, seek } = useWaveframe('https://example.com/audio.mp3');
|
|
454
|
+
*
|
|
455
|
+
* return (
|
|
456
|
+
* <div>
|
|
457
|
+
* <button onClick={togglePlay}>{state.isPlaying ? 'Pause' : 'Play'}</button>
|
|
458
|
+
* <div onClick={(e) => seek(0.5)}>Seek to Middle</div>
|
|
459
|
+
* </div>
|
|
460
|
+
* );
|
|
461
|
+
* ```
|
|
462
|
+
*/
|
|
463
|
+
declare const useWaveframe: (media: string | Blob | undefined, options?: UseWaveframeOptions) => {
|
|
464
|
+
/** The current reactive state of the engine */
|
|
465
|
+
state: EngineState;
|
|
466
|
+
/** The raw WaveframeEngine instance for advanced usage */
|
|
467
|
+
engine: WaveframeEngine;
|
|
468
|
+
/** Toggles playback between playing and paused */
|
|
469
|
+
togglePlay: () => void;
|
|
470
|
+
/** Starts audio playback */
|
|
471
|
+
play: () => void;
|
|
472
|
+
/** Pauses audio playback */
|
|
473
|
+
pause: () => void;
|
|
474
|
+
/** Seeks to a specific percentage (0-1) */
|
|
475
|
+
seek: (percentage: number) => void;
|
|
476
|
+
/** Sets the playback volume (0-1) */
|
|
477
|
+
setVolume: (v: number) => void;
|
|
478
|
+
/** Mutes or unmutes the audio */
|
|
479
|
+
setMuted: (m: boolean) => void;
|
|
480
|
+
/** Manually triggers a re-analysis of the current media */
|
|
481
|
+
analyze: (samples?: number) => Promise<void>;
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* A React hook that synchronizes a WaveframeEngine's state with a React component.
|
|
486
|
+
*
|
|
487
|
+
* It uses `useSyncExternalStore` for high-performance updates, ensuring that
|
|
488
|
+
* the component only re-renders when the engine's state snapshot actually changes.
|
|
489
|
+
*
|
|
490
|
+
* @param engine The WaveframeEngine instance to subscribe to.
|
|
491
|
+
* @returns The current EngineState (isPlaying, currentTime, peaks, etc.).
|
|
492
|
+
*
|
|
493
|
+
* @example
|
|
494
|
+
* ```tsx
|
|
495
|
+
* const MyPlayer = ({ engine }: { engine: WaveframeEngine }) => {
|
|
496
|
+
* const { isPlaying, currentTime, duration } = useWaveframeStore(engine);
|
|
497
|
+
*
|
|
498
|
+
* return (
|
|
499
|
+
* <div>
|
|
500
|
+
* <button onClick={() => engine.togglePlay()}>
|
|
501
|
+
* {isPlaying ? 'Pause' : 'Play'}
|
|
502
|
+
* </button>
|
|
503
|
+
* <p>{currentTime.toFixed(2)} / {duration.toFixed(2)}</p>
|
|
504
|
+
* </div>
|
|
505
|
+
* );
|
|
506
|
+
* };
|
|
507
|
+
* ```
|
|
508
|
+
*/
|
|
509
|
+
declare const useWaveframeStore: (engine: WaveframeEngine) => EngineState;
|
|
510
|
+
|
|
511
|
+
declare const useResampledPeaks: (peaks: number[], targetCount: number) => number[];
|
|
512
|
+
|
|
513
|
+
declare const useResizeObserver: (ref: React.RefObject<HTMLElement | null>) => number;
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Loads audio from a URL, decodes it, and generates a specific number of peaks (samples).
|
|
517
|
+
*
|
|
518
|
+
* This is a high-level utility function that internally manages a `PeakAnalyzer` instance.
|
|
519
|
+
*
|
|
520
|
+
* @param audioUrl The URL of the audio file to analyze.
|
|
521
|
+
* @param samples The number of peaks (bars) to generate. Defaults to 512.
|
|
522
|
+
* @returns A promise resolving to an array of normalized peak values (0 to 1).
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* ```typescript
|
|
526
|
+
* const peaks = await generatePeaks('https://example.com/audio.mp3', 256);
|
|
527
|
+
* ```
|
|
528
|
+
*/
|
|
529
|
+
declare const generatePeaks: (audioUrl: string, samples?: number) => Promise<number[]>;
|
|
530
|
+
/**
|
|
531
|
+
* Loads audio into memory as a Blob and returns a temporary Object URL.
|
|
532
|
+
*
|
|
533
|
+
* Useful for ensuring audio data is fully loaded locally before starting
|
|
534
|
+
* playback or analysis, which can help with CORS issues or slow networks.
|
|
535
|
+
*
|
|
536
|
+
* @param url The URL of the remote audio file.
|
|
537
|
+
* @returns A promise resolving to a temporary `blob:` URL.
|
|
538
|
+
*/
|
|
539
|
+
declare const loadAudioToMemory: (url: string) => Promise<string>;
|
|
540
|
+
/**
|
|
541
|
+
* Cleanup function to prevent memory leaks from Object URLs.
|
|
542
|
+
*
|
|
543
|
+
* Call this when a `blob:` URL is no longer needed (e.g., when the component unmounts).
|
|
544
|
+
*
|
|
545
|
+
* @param url The Object URL to revoke.
|
|
546
|
+
*/
|
|
547
|
+
declare const revokeAudioMemory: (url: string) => void;
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Formats seconds into a M:SS string
|
|
551
|
+
*/
|
|
552
|
+
declare const formatTime: (seconds: number) => string;
|
|
553
|
+
/**
|
|
554
|
+
* Resamples an array of peaks to a target count using bucket-max or linear interpolation
|
|
555
|
+
*/
|
|
556
|
+
declare const resamplePeaks: (peaks: number[], targetCount: number) => number[];
|
|
557
|
+
/**
|
|
558
|
+
* High-performance token-based syntax highlighter for React snippets
|
|
559
|
+
*/
|
|
560
|
+
declare const highlightCode: (code: string) => string[];
|
|
561
|
+
|
|
562
|
+
export { type EngineListener, type EngineState, PeakAnalyzer, PlayerCore, type PlayerListener, type PlayerState, type Resolution, type TrackInfo, type UseWaveframeOptions, Waveform, type WaveformConfig, WaveframeEngine, WaveframePlayer, type WaveframePlayerProps, type WaveframeTheme, formatTime, generatePeaks, highlightCode, loadAudioToMemory, resamplePeaks, revokeAudioMemory, useResampledPeaks, useResizeObserver, useWaveframe, useWaveframeStore };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import {memo,useRef,useEffect,useState,useMemo,useSyncExternalStore}from'react';import {jsxs,jsx}from'react/jsx-runtime';var T=class{audio;listeners=new Set;_state;constructor(){this.audio=new Audio,this._state={isPlaying:false,currentTime:0,duration:0,volume:1,muted:false,error:null},this.initListeners();}initListeners(){this.audio.addEventListener("play",()=>this.updateState({isPlaying:true,error:null})),this.audio.addEventListener("pause",()=>this.updateState({isPlaying:false})),this.audio.addEventListener("timeupdate",()=>this.updateState({currentTime:this.audio.currentTime})),this.audio.addEventListener("durationchange",()=>this.updateState({duration:this.audio.duration})),this.audio.addEventListener("volumechange",()=>this.updateState({volume:this.audio.volume,muted:this.audio.muted})),this.audio.addEventListener("ended",()=>this.updateState({isPlaying:false})),this.audio.addEventListener("error",()=>{let t=this.audio.error,e="Unknown audio error";if(t)switch(t.code){case t.MEDIA_ERR_ABORTED:e="Playback aborted";break;case t.MEDIA_ERR_NETWORK:e="Network error";break;case t.MEDIA_ERR_DECODE:e="Audio decoding failed";break;case t.MEDIA_ERR_SRC_NOT_SUPPORTED:e="Audio format not supported";break}this.updateState({isPlaying:false,error:e});});}updateState(t){this._state={...this._state,...t},this.notify();}notify(){this.listeners.forEach(t=>t(this._state));}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}get state(){return this._state}setSource(t){this.audio.src=t,this.audio.load(),this.updateState({error:null,currentTime:0,duration:0});}async play(){try{await this.audio.play();}catch(t){let e=t instanceof Error?t.message:"Playback failed";throw this.updateState({isPlaying:false,error:e}),t}}pause(){this.audio.pause();}async togglePlay(){if(this._state.isPlaying)this.pause();else try{await this.play();}catch{}}seek(t){this.audio.currentTime=t;}setVolume(t){this.audio.volume=t;}setMuted(t){this.audio.muted=t;}dispose(){this.pause(),this.audio.src="",this.listeners.clear();}};var R=class{audioCtx=null;constructor(){}getContext(){return this.audioCtx||(this.audioCtx=new(window.AudioContext||window.webkitAudioContext)),this.audioCtx}async generatePeaks(t,e=512){try{let o;if(typeof t=="string"){let c=await fetch(t);if(!c.ok)throw new Error(`Failed to fetch audio: ${c.statusText}`);o=await c.arrayBuffer();}else o=await t.arrayBuffer();let n=(await this.getContext().decodeAudioData(o)).getChannelData(0),s=Math.floor(n.length/e),l=[];for(let c=0;c<e;c++){let u=0,g=c*s,d=g+s;for(let y=g;y<d;y++){let S=Math.abs(n[y]);S>u&&(u=S);}l.push(u);}let x=Math.max(...l);return l.map(c=>c/(x||1))}catch(o){throw console.error("PeakAnalyzer Error:",o),o}}dispose(){this.audioCtx&&(this.audioCtx.close(),this.audioCtx=null);}};var W=class{player;analyzer;listeners=new Set;_state;_media=null;_objectUrl=null;constructor(){this.player=new T,this.analyzer=new R,this._state={...this.player.state,peaks:[],isAnalyzing:false,error:null},this.player.subscribe(t=>{this.updateState({...t});});}updateState(t){this._state={...this._state,...t},this.notify();}notify(){this.listeners.forEach(t=>t(this._state));}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getSnapshot(){return this._state}revokeOldSource(){this._objectUrl&&(URL.revokeObjectURL(this._objectUrl),this._objectUrl=null);}load(t,e){if(this._media!==t){this.revokeOldSource(),this._media=t;let i;typeof t=="string"?i=t:(this._objectUrl=URL.createObjectURL(t),i=this._objectUrl),this.player.setSource(i);let a=e&&e.length>0;this.updateState({peaks:e||[],isAnalyzing:false,error:null}),a||this.analyze();}else e&&e.length!==this._state.peaks.length&&this.updateState({peaks:e});}async analyze(t=512){if(!this._media){this.updateState({error:"No media loaded to analyze"});return}this.updateState({isAnalyzing:true,error:null});try{let e=await this.analyzer.generatePeaks(this._media,t);this.updateState({peaks:e,isAnalyzing:!1});}catch(e){this.updateState({isAnalyzing:false,error:e instanceof Error?e.message:"Analysis failed"});}}togglePlay(){this.player.togglePlay();}play(){this.player.play();}pause(){this.player.pause();}seek(t){let{duration:e}=this._state;e&&this.player.seek(t*e);}setVolume(t){this.player.setVolume(t);}setMuted(t){this.player.setMuted(t);}dispose(){this.revokeOldSource(),this.player.dispose(),this.analyzer.dispose(),this.listeners.clear();}};var q=r=>useSyncExternalStore(t=>r.subscribe(t),()=>r.getSnapshot());var Q=(r,t={})=>{let{peaks:e,engine:o}=t,i=useMemo(()=>o||new W,[o]),a=o||i,n=q(a);return useEffect(()=>{r&&a.load(r,e);},[a,r,e]),useEffect(()=>()=>{o||i.dispose();},[i,o]),{state:n,engine:a,togglePlay:()=>a.togglePlay(),play:()=>a.play(),pause:()=>a.pause(),seek:s=>a.seek(s),setVolume:s=>a.setVolume(s),setMuted:s=>a.setMuted(s),analyze:s=>a.analyze(s)}};var At=async(r,t=512)=>{let e=new R;try{return await e.generatePeaks(r,t)}finally{e.dispose();}},Lt=async r=>{let e=await(await fetch(r)).blob();return URL.createObjectURL(e)},jt=r=>{r&&r.startsWith("blob:")&&URL.revokeObjectURL(r);};var H=r=>{if(isNaN(r))return "0:00";let t=Math.floor(r/60),e=Math.floor(r%60);return `${t}:${e.toString().padStart(2,"0")}`},Y=(r,t)=>{if(r.length===0)return [];if(r.length===t)return r;let e=new Array(t),o=r.length/t;if(o>1)for(let i=0;i<t;i++){let a=0,n=Math.floor(i*o),s=Math.floor((i+1)*o);for(let l=n;l<s;l++)r[l]>a&&(a=r[l]);e[i]=a;}else for(let i=0;i<t;i++){let a=i*o,n=Math.floor(a),s=Math.min(n+1,r.length-1),l=a-n;e[i]=r[n]+(r[s]-r[n])*l;}return e},Wt=r=>r.split(`
|
|
3
|
+
`).map(t=>{let e=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),o={},i=0,a=(n,s)=>{let l=`__TOKEN_${i++}__`;return o[l]=`<span class="${s}">${n}</span>`,l};return e=e.replace(/("(?:[^"\\]|\\.)*")/g,n=>a(n,"text-[#ce9178]")),e=e.replace(/\b(\d+(\.\d+)?)\b/g,n=>a(n,"text-[#b5cea8]")),e=e.replace(/\b(WaveframePlayer)\b/g,n=>a(n,"text-[#4ec9b0]")),e=e.replace(/\b([a-z][a-zA-Z0-9]+)(?==)/g,n=>a(n,"text-[#9cdcfe]")),e=e.replace(/(<|>|\{|\}|\/|:|,)/g,'<span class="text-gray-500">$1</span>'),Object.entries(o).forEach(([n,s])=>{e=e.replace(n,s);}),e});var tt=(r,t)=>useMemo(()=>Y(r,t),[r,t]);var U=r=>{let[t,e]=useState(0);return useEffect(()=>{if(!r.current)return;let o=new ResizeObserver(i=>{for(let a of i)e(a.contentRect.width);});return o.observe(r.current),()=>o.disconnect()},[r]),t};var I=memo(({artworkUrl:r,title:t,isLoading:e})=>jsxs("div",{className:"relative flex-shrink-0 w-32 h-32 md:w-40 md:h-40 overflow-hidden rounded-[var(--wf-artwork-rounded,0.75rem)] shadow-lg group/artwork",children:[jsx("div",{className:`w-full h-full transition-all duration-700 ${e?"blur-md scale-110":""}`,children:r?jsx("img",{src:r,alt:t,className:"w-full h-full object-cover transition-transform duration-500 group-hover/artwork:scale-110"}):jsx("div",{className:"w-full h-full bg-gradient-to-br from-[var(--wf-placeholder-from,#fb923c)] to-[var(--wf-placeholder-to,#ec4899)] flex items-center justify-center",children:jsx("svg",{className:"w-16 h-16 text-white opacity-50",fill:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})})}),e&&jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/10 backdrop-blur-[1px]",children:jsx("div",{className:"w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin"})})]}));I.displayName="ArtworkOverlay";var K=memo(({peaks:r,currentTime:t,duration:e,waveColor:o,progressColor:i,height:a,onSeek:n,resolution:s="auto",barWidth:l=2,barGap:x=1})=>{let c=useRef(null),u=useRef(null),g=useRef(null),d=U(g);useEffect(()=>{let f=c.current,b=u.current;if(!f||!b)return;let h=f.getContext("2d"),p=b.getContext("2d");if(!h||!p)return;let k=window.devicePixelRatio||1,E=f.getBoundingClientRect(),M=E.width*k,N=E.height*k;[f,b].forEach(w=>{(w.width!==M||w.height!==N)&&(w.width=M,w.height=N);}),(()=>{if(r.length===0)return;let{width:w,height:m}=f;h.clearRect(0,0,w,m),p.clearRect(0,0,w,m);let B=r.length,A=w/B,P=typeof s=="number"?A*.7:l*k,D=typeof s=="number"?A*.3:x*k;h.lineCap="round",h.lineWidth=P,p.lineCap="round",p.lineWidth=P,r.forEach((L,C)=>{if(L<=0)return;let j=C*(P+D)+P/2,X=L*m*.8,$=(m-X)/2,Z=$+X;h.beginPath(),h.strokeStyle=o,h.moveTo(j,$),h.lineTo(j,Z),h.stroke(),p.beginPath(),p.strokeStyle=i,p.moveTo(j,$),p.lineTo(j,Z),p.stroke();});})();},[r,o,i,s,l,x,a]);let y=f=>{if(g.current&&e){let b=g.current.getBoundingClientRect(),h=f.clientX-b.left,p=Math.max(0,Math.min(1,h/b.width));n(p);}},S=e?t/e*100:0;return jsxs("div",{ref:g,className:"relative w-full cursor-pointer overflow-hidden",style:{height:`${a}px`},onClick:y,children:[jsx("canvas",{ref:c,className:"absolute inset-0 w-full h-full"}),jsx("div",{className:"absolute inset-0 h-full overflow-hidden transition-[width] duration-100 ease-linear pointer-events-none",style:{width:`${S}%`},children:jsx("canvas",{ref:u,className:"absolute h-full",style:{width:`${d}px`}})})]})});K.displayName="Waveform";var ut=memo(({media:r,peaks:t,artwork:e,title:o,artist:i,waveColor:a,progressColor:n,height:s=80,className:l="",style:x,resolution:c="auto",barWidth:u=2,barGap:g=1,theme:d,engine:y})=>{let{state:S,togglePlay:f,seek:b}=Q(r,{peaks:t,engine:y}),{isPlaying:h,currentTime:p,duration:k,peaks:E,isAnalyzing:M}=S,[N,O]=useState(typeof e=="string"?e:void 0);useEffect(()=>{if(e instanceof Blob){let C=URL.createObjectURL(e);return O(C),()=>URL.revokeObjectURL(C)}else O(e);},[e]);let w=useRef(null),m=U(w),B=useMemo(()=>typeof c=="number"?c:m>0?Math.max(1,Math.floor(m/(u+g))):E.length||1,[c,m,u,g,E.length]),A=tt(E,B),P=useMemo(()=>a||(d?d.bg==="#ffffff"?"#e5e7eb":"#374151":"#e5e7eb"),[a,d]),D=n||d?.primary||"#3b82f6",L=useMemo(()=>({...{"--wf-bg-color":d?.bg||"white","--wf-border-color":d?.border||"#f3f4f6","--wf-title-color":d?.text||"#111827","--wf-artist-color":d?.text||"#6b7280","--wf-time-color":d?.text||"#9ca3af","--wf-play-btn-bg":d?.primary||"#3b82f6","--wf-placeholder-from":d?.primary||"#fb923c","--wf-placeholder-to":d?.bg||"#ec4899"},...x}),[d,x]);return jsxs("div",{className:`group relative flex flex-col md:flex-row items-stretch gap-6 p-6 bg-[var(--wf-bg-color,white)] border border-[var(--wf-border-color,#f3f4f6)] rounded-[var(--wf-rounded,1rem)] shadow-xl hover:shadow-2xl transition-all duration-300 overflow-hidden ${l}`,style:L,children:[jsx(I,{artworkUrl:N,title:o,isLoading:M}),jsxs("div",{className:"flex-1 w-full flex flex-col min-w-0",children:[jsxs("div",{className:"flex items-center gap-4 mb-6",children:[jsx("button",{onClick:f,className:"w-12 h-12 md:w-14 md:h-14 flex-shrink-0 flex items-center justify-center rounded-full bg-[var(--wf-play-btn-bg,#3b82f6)] text-white shadow-[0_4px_12px_rgba(0,0,0,0.15)] hover:shadow-[0_6px_16px_rgba(0,0,0,0.2)] transition-all hover:scale-105 active:scale-95 cursor-pointer border-none outline-none group/play",children:h?jsx("svg",{className:"w-6 h-6 md:w-7 md:h-7",fill:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"})}):jsx("svg",{className:"w-6 h-6 md:w-7 md:h-7 ml-1",fill:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{d:"M8 5v14l11-7z"})})}),jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[jsxs("div",{className:"flex items-center justify-between gap-4",children:[i&&jsx("p",{className:"text-[10px] md:text-xs font-bold uppercase text-[var(--wf-artist-color,#6b7280)] opacity-60 tracking-[0.1em] line-clamp-1",children:i}),jsxs("div",{className:"text-[10px] font-mono text-[var(--wf-time-color,#9ca3af)] tabular-nums flex-shrink-0",children:[H(p)," / ",H(k)]})]}),o&&jsx("h3",{className:"text-lg md:text-xl font-black text-[var(--wf-title-color,#111827)] tracking-tight line-clamp-1 mt-0.5 leading-tight",children:o})]})]}),jsx("div",{className:"mt-auto",ref:w,children:jsx(K,{peaks:A,currentTime:p,duration:k,waveColor:P,progressColor:D,height:s,onSeek:b,resolution:c,barWidth:u,barGap:g})})]})]})});ut.displayName="WaveframePlayer";export{R as PeakAnalyzer,T as PlayerCore,K as Waveform,W as WaveframeEngine,ut as WaveframePlayer,H as formatTime,At as generatePeaks,Wt as highlightCode,Lt as loadAudioToMemory,Y as resamplePeaks,jt as revokeAudioMemory,tt as useResampledPeaks,U as useResizeObserver,Q as useWaveframe,q as useWaveframeStore};//# sourceMappingURL=index.js.map
|
|
4
|
+
//# sourceMappingURL=index.js.map
|