audiosprite

repository·master·Indexed 20 days ago

https://github.com/tonistiigi/audiosprite

An FFmpeg wrapper that concatenates multiple small audio files into a single audio sprite file and generates a corresponding JSON metadata file. It supports various export formats (ogg, m4a, mp3, ac3) and JSON manifest formats compatible with Howler.js, Jukebox, and CreateJS to reduce HTTP requests and latency on web and mobile devices. Available as both a CLI tool and a Node.js API.

Tokens
3.7K
Snippets
8
Records
13
Agent score
71%

What's inside audiosprite

  1. Integrate with LimeJS framework

    master

    To use audiosprite assets with the digitalfruit/limejs framework:

    1. Generate LimeJS asset: Use the lime.py tool to convert the generated JSON file into a LimeJS asset.

      bin/lime.py gensoy path/to/mygameaudio.json
    2. Play audio in code: Use the AudioMap class to load the asset and play specific sprites.

    Tip: Use the --rawparts=mp3 option when running audiosprite to allow LimeJS to automatically switch to the Web Audio API when supported by the client.

    goog.require('lime.audio.AudioMap');
    goog.require('lime.ASSETS.mygameaudio.json');
    
    var audio = new lime.audio.AudioMap(lime.ASSETS.mygameaudio.json);
    // ...
    audio.play('click');
    goog.require('lime.audio.AudioMap');
    goog.require('lime.ASSETS.mygameaudio.json');
    
    var audio = new lime.audio.AudioMap(lime.ASSETS.mygameaudio.json);
    ...
    audio.play('click');
  2. Install FFmpeg dependencies

    master

    macOS

    Use Homebrew to install ffmpeg with theora and libvorbis support:

    brew install ffmpeg --with-theora --with-libvorbis

    Windows

    1. Install Node.js.
    2. Use Git Bash instead of Command Prompt or PowerShell.
    3. Download ffmpeg and add the bin directory to your PATH:
      export PATH=$PATH:path/to/ffmpeg/bin

    Note: IMA-ADPCM (the fastest iPhone format) is only generated on macOS.

  3. How audiosprite manifest formats work

    master

    The format option determines the structure of the returned JSON object, allowing it to be used directly with different web audio libraries:

    • default: Returns the raw internal structure containing resources (array of file paths) and spritemap (object mapping names to { start, end, loop } in seconds).
    • howler: Formatted for Howler.js v1. Uses urls for the resource list and sprite for timing. Timing is in milliseconds and includes a loop boolean: [startMs, endMs, loopBool].
    • howler2: Formatted for Howler.js v2. Uses src instead of urls. Timing is in milliseconds and includes a loop boolean: [startMs, endMs, loopBool].
    • createjs: Formatted for CreateJS. Uses src for the main file and data.audioSprite array containing objects with id, startTime (ms), and duration (ms).
  4. Use the audiosprite Node.js API

    master

    You can use audiosprite as a module in your Node.js applications.

    var audiosprite = require('audiosprite')
    
    var files = ['file1.mp3', 'file2.mp3']
    var opts = {output: 'result'}
    
    audiosprite(files, opts, function(err, obj) {
      if (err) return console.error(err)
    
      console.log(JSON.stringify(obj, null, 2))
    })

    obj is the resulting JSON object containing the resources list and the spritemap definitions.

    var audiosprite = require('audiosprite')
    
    var files = ['file1.mp3', 'file2.mp3']
    var opts = {output: 'result'}
    
    audiosprite(files, opts, function(err, obj) {
      if (err) return console.error(err)
    
      console.log(JSON.stringify(obj, null, 2))
    })
  5. Configure audiosprite options

    master

    The following options can be passed to the audiosprite function to control the generation process:

    OptionDefaultDescription
    output'output'The base filename for the exported audio files (without extension).
    path''A prefix path added to the resource filenames in the JSON manifest.
    export'ogg,m4a,mp3,ac3'A comma-separated list of audio formats to export.
    formatnullThe JSON manifest format: 'howler', 'howler2', 'createjs', or 'default'.
    autoplaynullThe name of the resource to be set as the default autoplay item.
    loop[]An array of resource names that should be marked as loop: true in the manifest.
    silence0Duration (in seconds) of silence to add to the beginning of the sprite.
    gap1Duration (in seconds) of silence to add between each audio file.
    minlength0Minimum duration (in seconds) for each audio segment.
    bitrate128Audio bitrate in kbps.
    vbr-1Variable Bit Rate setting for MP3 (0-9).
    'vbr:vorbis'-1Variable Bit Rate setting for WebM/Vorbis (0-10).
    samplerate44100Audio sample rate in Hz.
    channels1Number of audio channels (1 for mono, 2 for stereo).
    rawparts''Comma-separated list of extensions to export as individual "raw" slices (e.g., 'mp3,wav').
    ignorerounding0If non-zero, prevents rounding silence gaps to the nearest second.
    logger{ debug, info, log }An object containing logging functions to capture internal process details.
  6. Reference: audiosprite CLI options

    master

    The following options are available for the audiosprite command line tool:

    OptionFlagDescription
    --output-oName for the output files. [default: "output"]
    --path-uPath for files to be used on final JSON. [default: ""]
    --export-eLimit exported file types. Comma separated extension list. [default: "ogg,m4a,mp3,ac3"]
    --format-fFormat of the output JSON file (jukebox, howler, howler2, createjs). [default: "jukebox"]
    --log-lLog level (debug, info, notice, warning, error). [default: "info"]
    --autoplay-aAutoplay sprite name. [default: null]
    --loopLoop sprite name, can be passed multiple times. [default: null]
    --silence-sAdd special "silence" track with specified duration. [default: 0]
    --gap-gSilence gap between sounds (in seconds). [default: 1]
    --minlength-mMinimum sound duration (in seconds). [default: 0]
    --bitrate-bBit rate. Works for: ac3, mp3, mp4, m4a, ogg. [default: 128]
    --vbr-vVBR [0-9]. Works for: mp3. -1 disables VBR. [default: -1]
    --samplerate-rSample rate. [default: 44100]
    --channels-cNumber of channels (1=mono, 2=stereo). [default: 1]
    --rawparts-pInclude raw slices (for Web Audio API) in specified formats. [default: ""]
    --ignorerounding-iBypass sound placement on whole second boundaries (0=round, 1=bypass). [default: 0]
    info: Usage: audiosprite [options] file1.mp3 file2.mp3 *.wav
    info: Options:
      --output, -o          Name for the output files.                                               [default: "output"]
      --path, -u            Path for files to be used on final JSON.                                 [default: ""]
      --export, -e          Limit exported file types. Comma separated extension list.               [default: "ogg,m4a,mp3,ac3"]
      --format, -f          Format of the output JSON file (jukebox, howler, howler2, createjs).     [default: "jukebox"]
      --log, -l             Log level (debug, info, notice, warning, error).                         [default: "info"]
      --autoplay, -a        Autoplay sprite name.                                                    [default: null]
      --loop                Loop sprite name, can be passed multiple times.                          [default: null]
      --silence, -s         Add special "silence" track with specified duration.                     [default: 0]
      --gap, -g             Silence gap between sounds (in seconds).                                 [default: 1]
      --minlength, -m       Minimum sound duration (in seconds).                                     [default: 0]
      --bitrate, -b         Bit rate. Works for: ac3, mp3, mp4, m4a, ogg.                            [default: 128]
      --vbr, -v             VBR [0-9]. Works for: mp3. -1 disables VBR.                               [default: -1]
      --samplerate, -r      Sample rate.                                                               [default: 44100]
      --channels, -c         Number of channels (1=mono, 2=stereo).                                   [default: 1]
      --rawparts, -p        Include raw slices(for Web Audio API) in specified formats.              [default: ""]
      --ignorerounding, -i  Bypass sound placement on whole second boundaries (0=round,1=bypass).     [default: 0]
      --help, -h            Show this help message.
  7. Use the audiosprite CLI

    master

    The audiosprite CLI takes multiple audio files and combines them into a single file with silent gaps between parts. It exports multiple audio formats and a JSON metadata file compatible with frameworks like Howler.js or Jukebox.

    Basic Syntax:

    audiosprite [options] file1.mp3 file2.mp3 *.wav

    Example: This command combines bg_loop.wav and all .mp3 files, sets bg_loop to autoplay, and names the output mygameaudio.

    audiosprite --autoplay bg_loop --output mygameaudio bg_loop.wav *.mp3
  8. Use audiosprite to combine audio files

    master

    The audiosprite function takes a list of audio files and combines them into a single large audio file (the sprite) and generates a JSON manifest (the spritemap) that defines the start and end times for each original file. This is useful for reducing HTTP requests in web applications by loading one large audio file instead of many small ones.

    Requirements:

    • ffmpeg must be installed and available on your system path.
    • If exporting to caf format, afconvert is required (macOS only).

    Arguments:

    1. files: An array of file paths or glob patterns (e.g., ['sounds/*.mp3']).
    2. opts (optional): An options object to configure output, formats, and metadata.
    3. callback (optional): A function called with (err, json) upon completion.
    const audiosprite = require('./audiosprite');
    
    const files = ['file1.mp3', 'file2.wav'];
    const opts = {
      output: 'output/sprite',
      export: 'mp3,ogg',
      format: 'howler2'
    };
    
    audiosprite(files, opts, (err, json) => {
      if (err) throw err;
      console.log('Generated manifest:', json);
    });
  9. Configure audiosprite advanced and logging options

    master

    Additional flags for raw data and logging:

    OptionAliasDefaultDescription
    --rawparts-p''Include raw slices (for Web Audio API) in specified formats.
    --log-linfoLog level (debug, info, notice, warning, error).
    --help-hN/AShow this help message.
  10. Configure audiosprite CLI output and format

    master

    Use these options to control the naming, file types, and JSON structure of the exported assets.

    OptionAliasDefaultDescription
    --output-ooutputName for the output files (the JSON will be named [output].json).
    --path-u''Path for files to be used on final JSON.
    --export-eogg,m4a,mp3,ac3Limit exported file types. Comma separated extension list.
    --format-fjukeboxFormat of the output JSON file (jukebox, howler, howler2, createjs).
    # Example: Exporting to mp3 and howler format
    audiosprite -o my_sprite -e mp3 -f howler sound1.wav sound2.wav
  11. Configure audiosprite sprite behavior and timing

    master

    Adjust how sounds are positioned and played within the sprite sheet:

    OptionAliasDefaultDescription
    --autoplay-anullAutoplay sprite name.
    --loop(none)nullLoop sprite name. Can be passed multiple times to specify multiple looping sprites.
    --silence-s0Add special "silence" track with specified duration.
    --gap-g1Silence gap between sounds (in seconds).
    --minlength-m0Minimum sound duration (in seconds).
    --ignorerounding-i0Bypass sound placement on whole second boundaries (0=round, 1=bypass).