Sound Basics

Playing

Creation of a sound is simple. Normally play returns the SoundInstance, but in this case it does not because the sound is not preloaded.

const sound = PIXI.sound.Sound.from('resources/boing.mp3');
sound.play();

To start playing the sound immediately after load is finished use the autoPlay flag.

PIXI.sound.Sound.from({
    url: 'resources/mechanical.mp3',
    autoPlay: true,
    complete: function() {
        console.log('Sound finished');
    }
});

Globally, you can also use the PIXI.sound library methods (add, play) for adding and playing a sound as well.

PIXI.sound.add('bird', 'resources/bird.mp3');
PIXI.sound.play('bird');

You can set options when playing a sound

PIXI.sound.Sound.from({
    url: 'resources/bird.mp3',
    preload: true,
    loaded: function(err, sound) {
        sound.play({
            volume: 0.1,
            start: 0,
            end: 1,
        });
    }
});

You can also set filters for different instances, in this demo you will hear two birds sounds, one is the left, one on the right.

PIXI.sound.Sound.from({
    url: 'resources/bird.mp3',
    preload: true,
    loaded: function(err, sound) {
        // sound.filters = [
        //     new PIXI.sound.filters.TelephoneFilter(),
        // ];
        sound.volume = 0.5;
        sound.play({
            filters: [
                new PIXI.sound.filters.StereoFilter(-1),
            ],
        });
        setTimeout(function () {
            sound.play({
                filters: [
                    new PIXI.sound.filters.StereoFilter(1),
                ],
            });
        }, 50);
    }
});

Filetypes

Not all web-browsers support different file extensions for audio playback. Setup fallback formats easily by useing the a glob-like expression for the file extension. This will prioritize format from left to right.

PIXI.Assets.add({ alias: 'applause', src: 'resources/applause.{ogg,mp3}' });
PIXI.Assets.load('applause').then(sound => sound.play());

Alternatively, if you don't plan to use Assets (typically because you're using a bundler like Parcel or Webpack), but you still would like to resolve multiple files, you can choose from multiple URLs.

const sound = PIXI.sound.add('applause', [
    'resources/applause.ogg',
    'resources/applause.mp3'
]);
sound.play();

Preloading

Preloading a sound can be enabled by passing in the preload flag. You can listen for when the sound is loaded by using the loaded callback.

PIXI.sound.Sound.from({
    url: 'resources/bird.mp3',
    preload: true,
    loaded: function(err, sound) {
        sound.play();
    }
});

PIXI's loader can be used to load Sound assets. This returns the Sound object on the Resource's sound property.

PIXI.Assets.add({ alias: 'bird', src: 'resources/bird.mp3' });
PIXI.Assets.load('bird').then(sound => sound.play());

Volume

Volume can be set initially by using the object constructor

const sound = PIXI.sound.Sound.from({
    url: 'resources/boing.mp3',
    volume: 0.25
});
sound.play();

Volume can also be set by changing the volume property.

const sound = PIXI.sound.Sound.from('resources/boing.mp3');
sound.volume = 0.25;
sound.play();

Events

Preloaded sounds return a SoundInstance object which can be used to listen to playback events such as a the progress and end.

PIXI.sound.Sound.from({
    url: 'resources/boing.mp3',
    preload: true,
    loaded: function(err, sound) {
        const instance = sound.play();
        instance.on('progress', function(progress) {
            console.log('Amount played: ', Math.round(progress * 100) + '%');
        });
        instance.on('end', function() {
            console.log('Sound finished playing');
        });
    }
});

Library

Library is the simplest way to create a cache of sounds.

PIXI.sound.add('boing', 'resources/boing.mp3');
PIXI.sound.play('boing');

Library utilities are available to help manage the cache of sounds.

PIXI.sound.add({
    boing: 'resources/boing.mp3',
    bird: 'resources/bird.mp3',
    mechanical: 'resources/mechanical.mp3'
});
PIXI.sound.play('boing');
PIXI.sound.play('bird');
PIXI.sound.play('mechanical');

Couple of convenience methods (find, exist, duration) for manipulating and checking sounds.

PIXI.sound.add('boing', {
    url: 'resources/boing.mp3',
    preload: true,
    loaded: function() {
        // duration can only be used once the sound is loaded
        console.log('Duration: ', PIXI.sound.duration('boing'), 'seconds');
    }
});
console.log('Exists?', PIXI.sound.exists('boing'));
console.log('Sound: ', PIXI.sound.find('boing'));

Utilities

First setup an Application to render the waveform.

window.waveform = new PIXI.Application();
window.waveform.init({
    width: 1024,
    height: 128,
    canvas: document.getElementById('waveform'),
    backgroundColor: 0xffffff
});
PIXI.Assets.add({ alias: 'applause', src: 'resources/applause.mp3' });
const sound = await PIXI.Assets.load('applause');
const baseTexture = PIXI.sound.utils.render(sound, {
    width: waveform.renderer.width,
    height: waveform.renderer.height,
    fill: '#999'
});
const playhead = new PIXI.Graphics()
    .rect(0, 0, 1, waveform.renderer.height)
    .fill(0xff0000);
const sprite = new PIXI.Sprite(
    new PIXI.Texture(baseTexture)
);
waveform.stage.addChild(sprite, playhead);
sound.play().on('progress', function(value) {
    playhead.x = baseTexture.width * value;
});

Create a simple sine-wave tone.

const sound = PIXI.sound.utils.sineTone(523.251, 3);
sound.play();

There's a utility method for playing a sound once. It is immediately destroyed and after this.

PIXI.sound.utils.playOnce('resources/mechanical.mp3', function() {
    console.log('Sound finished');
});

Stream

You can get the audio stream by StreamFilter

const stream = new MediaStream();
const recorder = new MediaRecorder(stream);
const streamFilter = new PIXI.sound.filters.StreamFilter();

// attach audio stream
streamFilter.stream.getAudioTracks().forEach(function (track) {
    stream.addTrack(track);
});
// process recorded data
recorder.ondataavailable = function (e) {
    if (e.data.size == 0) {
        console.error('no data available');
        return;
    }
    const blob = new Blob([e.data], {
      type: recorder.mimeType,
    });
    // You can download the audio file or upload the Blob to server
    const url = URL.createObjectURL(blob);
    PIXI.sound.filtersAll = []; // remove filters for recorded sound
    PIXI.sound.Sound.from({
        url: url,
        autoPlay: true,
    });
};
// apply filters
PIXI.sound.filtersAll = [
    new PIXI.sound.filters.TelephoneFilter(),
    new PIXI.sound.filters.StereoFilter(),
    // You need to place StreamFilter at the end of filters list,
    // so that the stream will have the effect of other filters.
    streamFilter,
];
// load and play sound
PIXI.sound.Sound.from({
    url: 'resources/boing.mp3',
    autoPlay: true,
    loaded: function () {
        recorder.start();
    },
    complete: function () {
        recorder.stop();
    }
});