pixijs / sound

WebAudio API playback library, with filters. Modern audio playback for modern browsers.
https://pixijs.io/sound/examples/
MIT License
409 stars 67 forks source link

global sprite aliases? #267

Open reececomo opened 5 months ago

reececomo commented 5 months ago

It would be neat if one could somehow alias audio sprites globally, similar to the texture cache for Spritesheets.

// Assume we've loaded two sound sprites:
//   - mySoundSprite1.sprites: [ 'laugh, 'sneeze' ]
//   - mySoundSprite2.sprites: [ 'boo', 'cheer', 'cry' ]

import { sound } from '@pixi/sound';

sound.play('boo', { volume: 0.75 });
sound.play('laugh', { volume: 0.5 });

It would make working with multiple audio sprites a lil slicker. As a workaround we've got something like this:

import { sound as pixiSound } from '@pixi/sound';
import { Music, SoundFx } from './my-assetpack-generated-constants';

export class SoundManager {
  /** reverse map of children -> parents */
  public childSpriteAliases = Map<Sounds, string>();

  public async play(alias: Music | SoundFx, options: PlayOptions = {}): Promise<IMediaInstance | undefined> {
    const parentSound = this.childSpriteAliases.get(alias);

    // play sprite
    if (parentSound) {
      return pixiSound.play(parentSound, { ...options, sprite: alias });
    }

    // play other ...
    return pixiSound.play(alias, options);
  }

  // ...
}

(And then in our audiosprite loader we've added some custom logic to inject those aliases on load.)