UNPKG

audio-tracker

Version:

A headless JavaScript library that gives you full control over web audio — playback, tracking, and Media Session integration made simple.

307 lines 10.4 kB
export { mediaSessionModule } from "./modules/mediaSessionModule"; export { timestampModule } from "./modules/timestampModule"; /** * Configuration options for AudioTracker initialization */ interface AudioTrackerOptions { preload?: "none" | "metadata" | "auto"; loop?: boolean; muted?: boolean; autoplay?: boolean; crossOrigin?: "anonymous" | "use-credentials" | null; volume?: number; } /** * Callback functions for audio events */ interface AudioCallbacks { onPlay?: () => void; onPause?: () => void; onEnded?: () => void; onTimeUpdate?: (currentTime: number) => void; onRateChange?: (rate: number) => void; onVolumeChange?: (volume: number) => void; onMuteChange?: (isMuted: boolean) => void; onBufferChange?: (bufferedTime: number) => void; onBufferPercentageChange?: (percentage: number) => void; onPlaying?: () => void; onSeeking?: (currentTime: number) => void; onLoadStart?: () => void; onCanPlay?: () => void; onWaiting?: () => void; onStalled?: () => void; onError?: (error: MediaError | null) => void; onDurationChange?: (duration: number) => void; } /** * Type for module functions that can extend AudioTracker functionality */ type AudioModule = (tracker: AudioTracker) => void | (() => void); /** * A headless JavaScript library that gives you full control over web audio with advanced tracking and control features. * Provides a clean API for audio manipulation, event handling, and modular extensions. */ export default class AudioTracker { private audio; private isExternalAudio; private options; private duration; private previousMutedState; private callbacks; private subscribers; private boundHandlers; private cleanupFunctions; constructor(audioSource: string | HTMLAudioElement, options?: AudioTrackerOptions); /** * Subscribe to audio element DOM events * @param eventName - Name of the audio event (e.g., 'play', 'pause', 'timeupdate') * @param callback - Function to execute when event fires * @example * tracker.subscribe('play', () => console.log('Audio started playing')); */ subscribe(eventName: string, callback: (event: Event) => void): void; /** * Unsubscribe from audio element DOM events * @param eventName - Name of the audio event * @param callback - The specific callback function to remove * @example * const handler = () => console.log('Playing'); * tracker.subscribe('play', handler); * tracker.unsubscribe('play', handler); */ unsubscribe(eventName: string, callback: (event: Event) => void): void; private _attachDOMListener; private _detachDOMListener; /** * Initialize AudioTracker with callback functions for various audio events * @param callbacks - Object containing callback functions for audio events * @returns The AudioTracker instance for method chaining * @example * tracker.init({ * onPlay: () => console.log('Playing'), * onTimeUpdate: (time) => console.log(`Current time: ${time}`), * onEnded: () => console.log('Playback finished') * }); */ init(callbacks?: AudioCallbacks): this; private updateBuffer; /** * Extend AudioTracker functionality with a module * @param module - Function that receives the tracker instance and returns an optional cleanup function * @returns The AudioTracker instance for method chaining * @example * tracker.use(mediaSessionModule).use(timestampModule); */ use(module: AudioModule): this; /** * Start audio playback * @returns Promise that resolves when playback begins * @example * await tracker.play(); */ play(): Promise<void>; /** * Pause audio playback * @example * tracker.pause(); */ pause(): void; /** * Toggle playback state between play and pause * @returns Promise that resolves when playback starts or void if paused * @example * await tracker.togglePlay(); */ togglePlay(): Promise<void> | void; /** * Seek to a specific time position in the audio * @param time - Time position in seconds * @example * tracker.seekTo(30); // Jump to 30 seconds */ seekTo(time: number): void; /** * Skip forward by a specified number of seconds * @param seconds - Number of seconds to skip forward (default: 10) * @example * tracker.forward(15); // Skip forward 15 seconds */ forward(seconds?: number): void; /** * Skip backward by a specified number of seconds * @param seconds - Number of seconds to skip backward (default: 10) * @example * tracker.backward(15); // Skip back 15 seconds */ backward(seconds?: number): void; /** * Set the audio volume level * @param value - Volume level from 0 to 100 * @example * tracker.setVolume(75); // Set volume to 75% */ setVolume(value: number): void; /** * Get the current volume level * @returns Current volume as a percentage (0-100) * @example * const volume = tracker.getVolume(); // Returns 75 */ getVolume(): number; /** * Set the muted state of the audio * @param muted - True to mute, false to unmute * @example * tracker.setMuted(true); // Mute audio */ setMuted(muted: boolean): void; /** * Toggle the muted state of the audio * @returns The new muted state (true if now muted, false if unmuted) * @example * const isMuted = tracker.toggleMute(); // Toggle and get new state */ toggleMute(): boolean; /** * Check if audio is currently muted * @returns True if muted, false otherwise * @example * if (tracker.isMuted()) console.log('Audio is muted'); */ isMuted(): boolean; /** * Set the playback speed rate * @param rate - Playback rate (0.5 = half speed, 1.0 = normal, 2.0 = double speed) * @example * tracker.setPlaybackRate(1.5); // Play at 1.5x speed */ setPlaybackRate(rate: number): void; /** * Get the current playback speed rate * @returns Current playback rate * @example * const rate = tracker.getPlaybackRate(); // Returns 1.5 */ getPlaybackRate(): number; /** * Enable or disable audio looping * @param loop - True to enable loop, false to disable * @example * tracker.setLoop(true); // Enable continuous looping */ setLoop(loop: boolean): void; /** * Check if audio looping is enabled * @returns True if looping is enabled * @example * if (tracker.isLooping()) console.log('Loop is enabled'); */ isLooping(): boolean; /** * Enable or disable autoplay * @param autoplay - True to enable autoplay, false to disable * @example * tracker.setAutoplay(true); // Enable autoplay */ setAutoplay(autoplay: boolean): void; /** * Check if autoplay is enabled * @returns True if autoplay is enabled * @example * const hasAutoplay = tracker.getAutoplay(); */ getAutoplay(): boolean; /** * Set CORS settings for the audio element * @param crossOrigin - CORS setting ('anonymous', 'use-credentials', or null) * @example * tracker.setCrossOrigin('anonymous'); */ setCrossOrigin(crossOrigin: "anonymous" | "use-credentials" | null): void; /** * Get the current CORS setting * @returns Current crossOrigin value * @example * const cors = tracker.getCrossOrigin(); */ getCrossOrigin(): string | null; /** * Set the preload behavior for the audio * @param preload - Preload setting ('none', 'metadata', or 'auto') * @example * tracker.setPreload('metadata'); // Preload only metadata */ setPreload(preload: "none" | "metadata" | "auto"): void; /** * Get the current preload setting * @returns Current preload value * @example * const preload = tracker.getPreload(); */ getPreload(): string; /** * Get the ready state of the audio element * @returns Ready state (0: HAVE_NOTHING, 1: HAVE_METADATA, 2: HAVE_CURRENT_DATA, 3: HAVE_FUTURE_DATA, 4: HAVE_ENOUGH_DATA) * @example * const state = tracker.getReadyState(); */ getReadyState(): number; /** * Get the network state of the audio element * @returns Network state (0: NETWORK_EMPTY, 1: NETWORK_IDLE, 2: NETWORK_LOADING, 3: NETWORK_NO_SOURCE) * @example * const networkState = tracker.getNetworkState(); */ getNetworkState(): number; /** * Check if audio is currently playing * @returns True if audio is playing, false otherwise * @example * if (tracker.isPlaying()) console.log('Audio is playing'); */ isPlaying(): boolean; /** * Get the total duration of the audio * @returns Duration in seconds * @example * const duration = tracker.getDuration(); // Returns 180 (3 minutes) */ getDuration(): number; /** * Get the current playback time position * @returns Current time in seconds * @example * const currentTime = tracker.getCurrentTime(); // Returns 45.5 */ getCurrentTime(): number; /** * Get the remaining time until audio ends * @returns Remaining time in seconds * @example * const remaining = tracker.getTimeRemaining(); // Returns 134.5 */ getTimeRemaining(): number; /** * Format seconds into MM:SS format * @param seconds - Time in seconds to format * @returns Formatted time string (e.g., "3:45") * @example * const formatted = tracker.formatTime(225); // Returns "3:45" */ formatTime(seconds: number): string; /** * Get direct access to the underlying HTMLAudioElement * @returns The HTMLAudioElement instance * @example * const audioElement = tracker.getAudioElement(); * audioElement.addEventListener('canplaythrough', callback); */ getAudioElement(): HTMLAudioElement; /** * Clean up all resources and event listeners. Call this when done using the tracker. * @example * tracker.destroy(); // Clean up before removing component */ destroy(): void; } //# sourceMappingURL=index.d.ts.map