Search code examples
javascriptaudiotone.js

How to play a tone using an audiobuffer with Tone.Player?


Using Tone.js I'm able to play a sound using the following code

var player = new Tone.Player("./sounds/snare_drum.wav").toMaster();
player.autostart = true;

However when I try to do the same thing with an audiobuffer nothing happens.

var player = new Tone.Player(buffers[i]).toMaster();
player.autostart = true;
console.log(buffers[i]);

The console.log confirms there is an AudioBuffer

AudioBuffer { sampleRate: 44100, length: 83771, duration: 1.8995691609977323, numberOfChannels: 1 }

According to the documentation it should be able to take an url or an AudioBuffer. What am I doing wrong? Thanks.


Solution

  • According to the documentation

    player.autostart = true;
    

    starts the playback as soon as the file or buffer is loaded. Probably if the loading is already complete when you set the flag, then it is ignored and the playback is not started automatically. Since the AudioBuffer is almost certainly already loaded in memory, this could be the reason why the playback doesn't start.

    You can add a test to check the status of the audio stream: if it's not already loaded, then you set autostart to true and delay the start (to avoid starting a stream not yet loaded). If the audio stream is already loaded then you can safely start it manually.

    if (!player.loaded)
        player.autostart = true;
    else
        player.start();
    

    I have done a quick test both with a WAV file and with an AudioBuffer cases and it seems to work. Not sure if this is the best solution though.

    Hope this helps =)