waveframe 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,491 @@
1
+ import React 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
+ };
94
+ /**
95
+ * A callback function that receives the latest PlayerState.
96
+ */
97
+ type PlayerListener = (state: PlayerState) => void;
98
+ /**
99
+ * The internal core class responsible for managing the HTMLAudioElement.
100
+ *
101
+ * It handles raw playback logic, volume control, and synchronizes the
102
+ * internal `PlayerState` with DOM events from the underlying `Audio` instance.
103
+ */
104
+ declare class PlayerCore {
105
+ private audio;
106
+ private listeners;
107
+ private _state;
108
+ /**
109
+ * Initializes a new PlayerCore instance and sets up event listeners on a new Audio object.
110
+ */
111
+ constructor();
112
+ /**
113
+ * Subscribes to various HTMLMediaElement events to keep the internal state in sync.
114
+ */
115
+ private initListeners;
116
+ /**
117
+ * Updates the internal state and notifies subscribers.
118
+ */
119
+ private updateState;
120
+ /**
121
+ * Triggers all registered listener callbacks.
122
+ */
123
+ private notify;
124
+ /**
125
+ * Registers a listener for state updates.
126
+ * @param listener The callback function.
127
+ * @returns An unsubscribe function.
128
+ */
129
+ subscribe(listener: PlayerListener): () => boolean;
130
+ /**
131
+ * Returns the current playback state.
132
+ */
133
+ get state(): PlayerState;
134
+ /**
135
+ * Updates the source URL of the underlying audio element.
136
+ * @param url The audio source URL.
137
+ */
138
+ setSource(url: string): void;
139
+ /**
140
+ * Starts playback. Returns a promise that resolves when playback begins.
141
+ */
142
+ play(): Promise<void>;
143
+ /**
144
+ * Pauses playback.
145
+ */
146
+ pause(): void;
147
+ /**
148
+ * Toggles between play and pause states.
149
+ */
150
+ togglePlay(): void;
151
+ /**
152
+ * Seeks to a specific time.
153
+ * @param time Time in seconds.
154
+ */
155
+ seek(time: number): void;
156
+ /**
157
+ * Sets the volume level.
158
+ * @param volume Level from 0 to 1.
159
+ */
160
+ setVolume(volume: number): void;
161
+ /**
162
+ * Mutes or unmutes the audio element.
163
+ * @param muted Mute status.
164
+ */
165
+ setMuted(muted: boolean): void;
166
+ /**
167
+ * Cleans up the audio element and removes all listeners.
168
+ */
169
+ dispose(): void;
170
+ }
171
+
172
+ /**
173
+ * Represents the complete state of the Waveframe engine, combining playback and analysis.
174
+ */
175
+ type EngineState = PlayerState & {
176
+ /** The current set of generated or provided waveform peaks (0-1 range) */
177
+ peaks: number[];
178
+ /** Whether an audio analysis process is currently in progress */
179
+ isAnalyzing: boolean;
180
+ /** Any error message encountered during playback or analysis */
181
+ error: string | null;
182
+ };
183
+ /**
184
+ * A callback function that receives the latest EngineState.
185
+ */
186
+ type EngineListener = (state: EngineState) => void;
187
+ /**
188
+ * The orchestrator class for Waveframe.
189
+ *
190
+ * It manages the lifecycle of audio playback and waveform analysis, providing a unified
191
+ * store-like interface that can be easily consumed by React or other frameworks.
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const engine = new WaveframeEngine();
196
+ *
197
+ * // Load from URL (automatic analysis if peaks omitted)
198
+ * engine.load('https://example.com/audio.mp3');
199
+ *
200
+ * // Load from Blob with pre-computed peaks
201
+ * engine.load(myBlob, [0.1, 0.5, 0.8]);
202
+ *
203
+ * // Subscription
204
+ * const unsubscribe = engine.subscribe((state) => {
205
+ * console.log('Current time:', state.currentTime);
206
+ * });
207
+ * ```
208
+ */
209
+ declare class WaveframeEngine {
210
+ private player;
211
+ private analyzer;
212
+ private listeners;
213
+ private _state;
214
+ private _media;
215
+ private _objectUrl;
216
+ /**
217
+ * Creates a new instance of the WaveframeEngine.
218
+ * Initializes internal PlayerCore and PeakAnalyzer.
219
+ */
220
+ constructor();
221
+ /**
222
+ * Internal method to update the state and notify all subscribers.
223
+ */
224
+ private updateState;
225
+ /**
226
+ * Notifies all registered listeners of a state change.
227
+ */
228
+ private notify;
229
+ /**
230
+ * Registers a listener to be called whenever the engine state changes.
231
+ * @param listener The callback function.
232
+ * @returns An unsubscribe function.
233
+ */
234
+ subscribe(listener: EngineListener): () => boolean;
235
+ /**
236
+ * Returns a snapshot of the current engine state.
237
+ * Useful for `useSyncExternalStore`.
238
+ */
239
+ getSnapshot(): EngineState;
240
+ /**
241
+ * Revokes any existing Object URLs to prevent memory leaks.
242
+ */
243
+ private revokeOldSource;
244
+ /**
245
+ * Loads media (URL or Blob) into the player.
246
+ *
247
+ * If a string is passed, it's treated as a URL and used directly for playback.
248
+ * If a Blob is passed, an Object URL is created for playback.
249
+ *
250
+ * If `peaks` are not provided, it automatically triggers an analysis.
251
+ *
252
+ * @param media The audio source (URL string or Blob/File object).
253
+ * @param peaks Optional pre-generated peaks for the waveform.
254
+ */
255
+ load(media: string | Blob, peaks?: number[]): void;
256
+ /**
257
+ * Analyzes the current media to generate waveform peaks.
258
+ * @param samples The number of peaks to generate. Defaults to 512.
259
+ */
260
+ analyze(samples?: number): Promise<void>;
261
+ /**
262
+ * Toggles playback between playing and paused.
263
+ */
264
+ togglePlay(): void;
265
+ /**
266
+ * Starts audio playback.
267
+ */
268
+ play(): void;
269
+ /**
270
+ * Pauses audio playback.
271
+ */
272
+ pause(): void;
273
+ /**
274
+ * Seeks to a specific position in the track.
275
+ * @param percentage The seek position as a decimal (0 to 1).
276
+ */
277
+ seek(percentage: number): void;
278
+ /**
279
+ * Sets the playback volume.
280
+ * @param volume The volume level (0 to 1).
281
+ */
282
+ setVolume(volume: number): void;
283
+ /**
284
+ * Mutes or unmutes the audio.
285
+ * @param muted Whether the audio should be muted.
286
+ */
287
+ setMuted(muted: boolean): void;
288
+ /**
289
+ * Disposes of the engine, pausing playback and clearing all listeners and resources.
290
+ */
291
+ dispose(): void;
292
+ }
293
+
294
+ /**
295
+ * Props for the WaveframePlayer component
296
+ */
297
+ interface WaveframePlayerProps {
298
+ /**
299
+ * The audio source to play. Can be a URL string or a Blob/File object.
300
+ */
301
+ media?: string | Blob;
302
+ /**
303
+ * Optional pre-generated peaks for the waveform (0-1 range).
304
+ * If omitted or empty, the player will automatically analyze the media.
305
+ */
306
+ peaks?: number[];
307
+ /**
308
+ * The artwork source to display. Can be a URL string or a Blob/File object.
309
+ */
310
+ artwork?: string | Blob;
311
+ /**
312
+ * The title of the track
313
+ */
314
+ title?: string;
315
+ /**
316
+ * The artist of the track
317
+ */
318
+ artist?: string;
319
+ /**
320
+ * The base color of the waveform bars
321
+ * @default "#e5e7eb" (light) or "#374151" (dark)
322
+ */
323
+ waveColor?: string;
324
+ /**
325
+ * The color of the played progress part of the waveform
326
+ * @default theme.primary or "#3b82f6"
327
+ */
328
+ progressColor?: string;
329
+ /**
330
+ * The height of the waveform in pixels
331
+ * @default 80
332
+ */
333
+ height?: number;
334
+ /**
335
+ * Additional CSS classes for the container
336
+ */
337
+ className?: string;
338
+ /**
339
+ * Inline styles for the container
340
+ */
341
+ style?: React.CSSProperties;
342
+ /**
343
+ * The number of bars to render. Use 'auto' to fit the container width.
344
+ * @default "auto"
345
+ */
346
+ resolution?: number | 'auto';
347
+ /**
348
+ * The width of each bar in pixels (if resolution is 'auto')
349
+ * @default 2
350
+ */
351
+ barWidth?: number;
352
+ /**
353
+ * The gap between bars in pixels (if resolution is 'auto')
354
+ * @default 1
355
+ */
356
+ barGap?: number;
357
+ /**
358
+ * Custom theme configuration
359
+ */
360
+ theme?: WaveframeTheme;
361
+ /**
362
+ * Optional WaveframeEngine instance for external control.
363
+ * If provided, the player will sync with this engine instead of creating its own.
364
+ */
365
+ engine?: WaveframeEngine;
366
+ }
367
+ /**
368
+ * The standard "all-in-one" Waveframe player component.
369
+ *
370
+ * This component features a SoundCloud-inspired layout with a prominent
371
+ * play/pause button positioned next to the track metadata.
372
+ */
373
+ declare const WaveframePlayer: React.FC<WaveframePlayerProps>;
374
+
375
+ /**
376
+ * A specialized class for decoding audio data and generating waveform peaks.
377
+ *
378
+ * It leverages the Web Audio API (`AudioContext`) to process audio buffers
379
+ * and extract amplitude data for visualization.
380
+ */
381
+ declare class PeakAnalyzer {
382
+ private audioCtx;
383
+ /**
384
+ * Initializes the analyzer. AudioContext creation is deferred to the first use
385
+ * to comply with browser autoplay and resource management policies.
386
+ */
387
+ constructor();
388
+ /**
389
+ * Lazily creates or returns the existing AudioContext.
390
+ */
391
+ private getContext;
392
+ /**
393
+ * Processes media (URL or Blob) and generates a set of normalized peaks.
394
+ *
395
+ * @param media The URL string or Blob object to analyze.
396
+ * @param samples The number of peaks (bars) to generate. Defaults to 512.
397
+ * @returns A promise resolving to an array of normalized peak values (0 to 1).
398
+ *
399
+ * @example
400
+ * ```typescript
401
+ * const analyzer = new PeakAnalyzer();
402
+ *
403
+ * // Analyze from URL
404
+ * const peaksFromUrl = await analyzer.generatePeaks('https://example.com/audio.mp3');
405
+ *
406
+ * // Analyze from Blob
407
+ * const peaksFromBlob = await analyzer.generatePeaks(myAudioBlob);
408
+ * ```
409
+ */
410
+ generatePeaks(media: string | Blob, samples?: number): Promise<number[]>;
411
+ /**
412
+ * Closes the AudioContext and releases system audio resources.
413
+ */
414
+ dispose(): void;
415
+ }
416
+
417
+ /**
418
+ * A React hook that synchronizes a WaveframeEngine's state with a React component.
419
+ *
420
+ * It uses `useSyncExternalStore` for high-performance updates, ensuring that
421
+ * the component only re-renders when the engine's state snapshot actually changes.
422
+ *
423
+ * @param engine The WaveframeEngine instance to subscribe to.
424
+ * @returns The current EngineState (isPlaying, currentTime, peaks, etc.).
425
+ *
426
+ * @example
427
+ * ```tsx
428
+ * const MyPlayer = ({ engine }: { engine: WaveframeEngine }) => {
429
+ * const { isPlaying, currentTime, duration } = useWaveframeStore(engine);
430
+ *
431
+ * return (
432
+ * <div>
433
+ * <button onClick={() => engine.togglePlay()}>
434
+ * {isPlaying ? 'Pause' : 'Play'}
435
+ * </button>
436
+ * <p>{currentTime.toFixed(2)} / {duration.toFixed(2)}</p>
437
+ * </div>
438
+ * );
439
+ * };
440
+ * ```
441
+ */
442
+ declare const useWaveframeStore: (engine: WaveframeEngine) => EngineState;
443
+
444
+ /**
445
+ * Loads audio from a URL, decodes it, and generates a specific number of peaks (samples).
446
+ *
447
+ * This is a high-level utility function that internally manages a `PeakAnalyzer` instance.
448
+ *
449
+ * @param audioUrl The URL of the audio file to analyze.
450
+ * @param samples The number of peaks (bars) to generate. Defaults to 512.
451
+ * @returns A promise resolving to an array of normalized peak values (0 to 1).
452
+ *
453
+ * @example
454
+ * ```typescript
455
+ * const peaks = await generatePeaks('https://example.com/audio.mp3', 256);
456
+ * ```
457
+ */
458
+ declare const generatePeaks: (audioUrl: string, samples?: number) => Promise<number[]>;
459
+ /**
460
+ * Loads audio into memory as a Blob and returns a temporary Object URL.
461
+ *
462
+ * Useful for ensuring audio data is fully loaded locally before starting
463
+ * playback or analysis, which can help with CORS issues or slow networks.
464
+ *
465
+ * @param url The URL of the remote audio file.
466
+ * @returns A promise resolving to a temporary `blob:` URL.
467
+ */
468
+ declare const loadAudioToMemory: (url: string) => Promise<string>;
469
+ /**
470
+ * Cleanup function to prevent memory leaks from Object URLs.
471
+ *
472
+ * Call this when a `blob:` URL is no longer needed (e.g., when the component unmounts).
473
+ *
474
+ * @param url The Object URL to revoke.
475
+ */
476
+ declare const revokeAudioMemory: (url: string) => void;
477
+
478
+ /**
479
+ * Formats seconds into a M:SS string
480
+ */
481
+ declare const formatTime: (seconds: number) => string;
482
+ /**
483
+ * Resamples an array of peaks to a target count using bucket-max or linear interpolation
484
+ */
485
+ declare const resamplePeaks: (peaks: number[], targetCount: number) => number[];
486
+ /**
487
+ * High-performance token-based syntax highlighter for React snippets
488
+ */
489
+ declare const highlightCode: (code: string) => string[];
490
+
491
+ export { type EngineListener, type EngineState, PeakAnalyzer, PlayerCore, type PlayerListener, type PlayerState, type Resolution, type TrackInfo, type WaveformConfig, WaveframeEngine, WaveframePlayer, type WaveframePlayerProps, type WaveframeTheme, formatTime, generatePeaks, highlightCode, loadAudioToMemory, resamplePeaks, revokeAudioMemory, useWaveframeStore };