Audio Loom - v0.2.2
    Preparing search index...

    Class AudioManager

    AudioManager is a framework-agnostic audio management system built on the Web Audio API. It provides centralized control for organizing, playing, and managing audio assets in games and interactive applications.

    const audio = new AudioManager();

    // Initialize on user interaction (required by browsers)
    button.onclick = async () => {
    await audio.resumeAudioContext();
    };

    // Add and play sounds
    audio.addAudioTrack('explosion', 'sfx', '/sounds/explosion.wav');
    await audio.preload(['explosion']);
    audio.playAudioTrack('explosion');

    // Play background music with fade
    audio.addAudioTrack('music', 'music', '/sounds/track.mp3');
    await audio.fadeIn('music', 2000);
    Index

    Constructors

    Properties

    onTrackStart$: Observable<TrackStartEvent> = ...

    Observable that emits when a track starts playing.

    audio.onTrackStart$.subscribe(event => {
    console.log(`Playing: ${event.key} on channel ${event.channelId}`);
    });
    onTrackEnd$: Observable<TrackEndEvent> = ...

    Observable that emits when a track finishes playing.

    audio.onTrackEnd$.subscribe(event => {
    console.log(`Finished: ${event.key}`);
    });
    onLoadComplete$: Observable<LoadCompleteEvent> = ...

    Observable that emits when a track's metadata is loaded and ready to play.

    audio.onLoadComplete$.subscribe(event => {
    console.log(`Loaded: ${event.key}, duration: ${event.duration}s`);
    });
    onError$: Observable<AudioErrorEvent> = ...

    Observable that emits when an audio error occurs.

    audio.onError$.subscribe(event => {
    console.error(`Audio error: ${event.message}`, event.error);
    });

    Accessors

    • get loggingEnabled(): boolean

      Gets or sets whether debug logging is enabled. When enabled, the AudioManager logs internal operations to the console.

      Returns boolean

      false
      
    • set loggingEnabled(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    Methods

    • Initializes the AudioContext and resumes it if suspended. Call this method on user interaction to ensure audio playback works in browsers.

      Returns Promise<void>

      A promise that resolves when the AudioContext is ready.

      document.getElementById('startButton').onclick = async () => {
      await audio.initAudio();
      console.log('Audio ready!');
      };
    • Resumes a suspended AudioContext. Browsers require user interaction before allowing audio playback. Call this method in response to a user gesture (click, touch, keypress).

      Returns Promise<void>

      A promise that resolves when the AudioContext is resumed.

      playButton.onclick = async () => {
      await audio.resumeAudioContext();
      audio.playAudioTrack('click');
      };
    • Suspends the AudioContext to save resources when audio is not needed. Useful for pausing all audio when the application loses focus or enters background.

      Returns Promise<void>

      A promise that resolves when the AudioContext is suspended.

      document.addEventListener('visibilitychange', async () => {
      if (document.hidden) {
      await audio.suspendAudioContext();
      } else {
      await audio.resumeAudioContext();
      }
      });
    • Checks if the AudioContext is initialized and running.

      Returns boolean

      true if the AudioContext is ready for playback, false otherwise.

      if (!audio.isAudioReady()) {
      showMessage('Click to enable audio');
      }
    • Sets the master volume that affects all audio output. The value is clamped to the range [0, 1].

      Parameters

      • volume: number

        The master volume level (0 = silent, 1 = full volume).

      Returns void

      // Set master volume to 50%
      audio.setMasterVolume(0.5);

      // Mute all audio
      audio.setMasterVolume(0);
    • Gets the current master volume level.

      Returns number

      The master volume level (0-1).

      const volume = audio.getMasterVolume();
      volumeSlider.value = volume * 100;
    • Enables or disables audio playback for a specific group. When disabled, all sounds in the group are muted and continuous playback is paused.

      Parameters

      • group: string

        The audio group name (e.g., 'sfx', 'music', 'ambient').

      • enabled: boolean

        Whether the group should be enabled.

      Returns void

      // Mute sound effects
      audio.setAudioEnabled('sfx', false);

      // Re-enable sound effects
      audio.setAudioEnabled('sfx', true);
    • Sets the volume for a specific audio group. The value is clamped to the range [0, 1].

      Parameters

      • group: string

        The audio group name (e.g., 'sfx', 'music', 'ambient').

      • volume: number

        The volume level (0 = silent, 1 = full volume).

      Returns void

      // Set music volume to 70%
      audio.setAudioVolume('music', 0.7);

      // Set SFX volume from a slider
      audio.setAudioVolume('sfx', sfxSlider.value / 100);
    • Sets the maximum number of concurrent sounds for a group. When the limit is reached, new sounds in the group will not play.

      Parameters

      • group: string

        The audio group name.

      • maxConcurrent: number

        Maximum number of simultaneous sounds (minimum: 1).

      Returns void

      // Allow up to 4 concurrent footstep sounds
      audio.setGroupPoolSize('sfx', 4);

      // Allow more sounds for ambient group
      audio.setGroupPoolSize('ambient', 16);
    • Gets statistics about the audio pool for one or all groups.

      Parameters

      • Optionalgroup: string

        Optional group name. If omitted, returns stats for all groups.

      Returns PoolStats | PoolStats[]

      Pool statistics for the specified group, or an array of stats for all groups.

      // Get stats for a specific group
      const sfxStats = audio.getPoolStats('sfx');
      console.log(`SFX: ${sfxStats.inUse}/${sfxStats.maxConcurrent} in use`);

      // Get stats for all groups
      const allStats = audio.getPoolStats();
      allStats.forEach(stats => console.log(stats.group, stats.inUse));
    • Checks if all tracks for a key are fully loaded and ready to play.

      Parameters

      • key: string

        The audio key to check.

      Returns boolean

      true if all tracks for the key are loaded, false otherwise.

      if (audio.isLoaded('explosion')) {
      audio.playAudioTrack('explosion');
      } else {
      await audio.preload(['explosion']);
      }
    • Gets detailed loading status for a specific audio key.

      Parameters

      • key: string

        The audio key to check.

      Returns LoadStatus

      An object with total tracks, loaded count, and ready status.

      const status = audio.getLoadStatus('footsteps');
      console.log(`Loaded ${status.loaded}/${status.total} tracks`);
      if (status.ready) {
      console.log('All footstep sounds ready!');
      }
    • Preloads audio tracks into memory for low-latency playback. This is especially important for one-shot sounds (SFX) that need instant playback.

      Parameters

      • keys: string[]

        Array of audio keys to preload.

      Returns Promise<void>

      A promise that resolves when all tracks are loaded.

      If any track fails to load.

      // Preload during a loading screen
      async function loadGame() {
      showLoadingScreen();
      await audio.preload(['explosion', 'gunshot', 'footstep', 'jump']);
      hideLoadingScreen();
      }

      // Track loading progress
      audio.preload(['music1', 'music2']).then(() => {
      console.log('All music loaded');
      });
    • Registers an audio track with the manager. Multiple tracks can be registered under the same key for random variation.

      Parameters

      • key: string

        Unique identifier for the sound (e.g., 'explosion', 'footstep').

      • group: string

        Audio group for volume/mute control (e.g., 'sfx', 'music').

      • path: string

        URL or path to the audio file.

      Returns void

      // Add a single sound effect
      audio.addAudioTrack('explosion', 'sfx', '/sounds/explosion.wav');

      // Add multiple variations for the same key (random selection on play)
      audio.addAudioTrack('footstep', 'sfx', '/sounds/footstep1.wav');
      audio.addAudioTrack('footstep', 'sfx', '/sounds/footstep2.wav');
      audio.addAudioTrack('footstep', 'sfx', '/sounds/footstep3.wav');

      // Add background music
      audio.addAudioTrack('battle', 'music', '/music/battle-theme.mp3');
    • Plays a one-shot sound effect. If multiple tracks are registered under the key, one is selected randomly. The sound plays to completion and cannot be stopped or paused.

      Parameters

      • key: string

        The audio key to play.

      Returns void

      // Play a sound effect
      audio.playAudioTrack('explosion');

      // Play footstep (random variation if multiple tracks registered)
      audio.playAudioTrack('footstep');

      // Rapid fire - respects pool limits
      for (let i = 0; i < 10; i++) {
      audio.playAudioTrack('gunshot');
      }
    • Starts continuous playback on a channel. When a track ends, the next track is automatically played (looping through all tracks). Ideal for background music, ambient sounds, or any audio that should loop.

      Parameters

      • key: string

        The audio key to play.

      • channelId: string = DEFAULT_CHANNEL

        Optional channel identifier (default: 'default'). Use different channels for simultaneous playback (e.g., music + ambient).

      Returns void

      // Play background music on default channel
      audio.playContinuous('battle-music');

      // Play ambient sounds on a separate channel
      audio.playContinuous('forest-ambient', 'ambient');

      // Both play simultaneously and can be controlled independently
      audio.pauseContinuous('ambient'); // Pause only ambient
      audio.stopContinuous(); // Stop only default channel
    • Stops continuous playback on a channel and resets to the beginning.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to stop (default: 'default').

      Returns void

      // Stop the default channel
      audio.stopContinuous();

      // Stop a specific channel
      audio.stopContinuous('ambient');
    • Pauses continuous playback on a channel. The playback position is preserved and can be resumed with resumeContinuous.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to pause (default: 'default').

      Returns void

      // Pause when game is paused
      audio.pauseContinuous();

      // Pause ambient channel only
      audio.pauseContinuous('ambient');
    • Resumes paused continuous playback on a channel.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to resume (default: 'default').

      Returns void

      // Resume when game is unpaused
      audio.resumeContinuous();

      // Resume ambient channel only
      audio.resumeContinuous('ambient');
    • Starts playback with a gradual volume fade-in effect. Uses the Web Audio API's native gain automation for smooth transitions.

      Parameters

      • key: string

        The audio key to play.

      • duration: number

        Fade duration in milliseconds.

      • channelId: string = DEFAULT_CHANNEL

        The channel to use (default: 'default').

      Returns Promise<void>

      A promise that resolves when the fade-in completes.

      // Fade in background music over 2 seconds
      await audio.fadeIn('battle-music', 2000);

      // Fade in on a specific channel
      await audio.fadeIn('ambient', 3000, 'ambient');
    • Gradually fades out and stops the current playback on a channel. Uses the Web Audio API's native gain automation for smooth transitions.

      Parameters

      • duration: number

        Fade duration in milliseconds.

      • channelId: string = DEFAULT_CHANNEL

        The channel to fade out (default: 'default').

      Returns Promise<void>

      A promise that resolves when the fade-out completes and playback stops.

      // Fade out current music over 1.5 seconds
      await audio.fadeOut(1500);

      // Fade out ambient sounds
      await audio.fadeOut(2000, 'ambient');
    • Cross-fades from the current track to a new track on the same channel. The old track fades out while the new track fades in simultaneously.

      Parameters

      • key: string

        The audio key of the new track to play.

      • duration: number

        Cross-fade duration in milliseconds.

      • channelId: string = DEFAULT_CHANNEL

        The channel to cross-fade on (default: 'default').

      Returns Promise<void>

      A promise that resolves when the cross-fade completes.

      // Cross-fade to a new music track
      await audio.crossFade('boss-music', 2000);

      // Seamless transition between ambient tracks
      await audio.crossFade('cave-ambient', 3000, 'ambient');
    • Gets information about all active continuous playback channels.

      Returns { [channelId: string]: ChannelInfo }

      An object mapping channel IDs to their playback info.

      const channels = audio.getActiveChannels();
      Object.entries(channels).forEach(([id, info]) => {
      console.log(`Channel ${id}: ${info.key} (playing: ${info.isPlaying})`);
      });
    • Gets information about a specific playback channel.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to query (default: 'default').

      Returns ChannelInfo | null

      Channel info if active, or null if no playback on channel.

      const info = audio.getChannelInfo('music');
      if (info?.isPlaying) {
      console.log(`Now playing: ${info.key}`);
      }
    • Stops all continuous playback on all channels.

      Returns void

      // Stop all music/ambient when leaving a scene
      audio.stopAllContinuous();
    • Pauses all continuous playback on all channels.

      Returns void

      // Pause everything when game is paused
      audio.pauseAllContinuous();
    • Resumes all paused continuous playback on all channels.

      Returns void

      // Resume everything when game is unpaused
      audio.resumeAllContinuous();
    • Sets the playback speed/rate for a channel. The value is clamped to the range [0.25, 4.0].

      Parameters

      • rate: number

        Playback rate (1.0 = normal, 0.5 = half speed, 2.0 = double speed).

      • channelId: string = DEFAULT_CHANNEL

        The channel to modify (default: 'default').

      Returns void

      // Slow motion music effect
      audio.setPlaybackRate(0.5);

      // Fast forward
      audio.setPlaybackRate(2.0);

      // Reset to normal
      audio.setPlaybackRate(1.0);
    • Gets the current playback rate for a channel.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to query (default: 'default').

      Returns number | null

      The playback rate, or null if no playback on channel.

    • Seeks to a specific time position in the current track.

      Parameters

      • time: number

        Time position in seconds.

      • channelId: string = DEFAULT_CHANNEL

        The channel to seek (default: 'default').

      Returns void

      // Skip to 1 minute into the track
      audio.seek(60);

      // Restart from beginning
      audio.seek(0);
    • Gets the current playback time in seconds.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to query (default: 'default').

      Returns number | null

      Current time in seconds, or null if no playback on channel.

      const time = audio.getCurrentTime();
      if (time !== null) {
      progressBar.value = time;
      }
    • Gets the total duration of the current track in seconds.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to query (default: 'default').

      Returns number | null

      Duration in seconds, or null if unavailable.

      const duration = audio.getDuration();
      if (duration !== null) {
      console.log(`Track length: ${duration}s`);
      }
    • Gets comprehensive playback information for a channel.

      Parameters

      • channelId: string = DEFAULT_CHANNEL

        The channel to query (default: 'default').

      Returns PlaybackInfo | null

      Playback info including time, duration, rate, and volume.

      const info = audio.getPlaybackInfo();
      if (info) {
      console.log(`Playing: ${info.key}`);
      console.log(`Progress: ${info.currentTime}/${info.duration}s`);
      console.log(`Rate: ${info.playbackRate}x, Volume: ${info.volume}`);
      }
    • Stops all active one-shot sounds in a specific group. This immediately stops and cleans up all playing sounds that belong to the specified group.

      Parameters

      • group: string

        The group key to stop all sounds for (e.g., 'sfx', 'ui', 'ambient')

      Returns void

      // Stop all UI sounds when closing a menu
      audio.stopAudioGroup('ui');

      // Stop all SFX when pausing the game
      audio.stopAudioGroup('sfx');
    • Destroys the AudioManager and releases all resources. Stops all playback, disconnects all audio nodes, and closes the AudioContext. After calling destroy(), the AudioManager instance should not be used.

      Returns void

      // Clean up when leaving a game or unmounting a component
      audio.destroy();

      // React useEffect cleanup
      useEffect(() => {
      const audio = new AudioManager();
      return () => audio.destroy();
      }, []);