Search code examples
reactjselectronelectron-react-boilerplatetonejs

Load locally saved files to tonejs


I am trying to create an app with the electron-react boilerplate where i can create audio files.

I found Tone.js, which allows me to play sounds but loading the sample files seems close to impossible. Is there a way to give the audio data to Tone?

I am using Sampler but i dont know how to create the URLs to transmit the data


Solution

  • I ended up using a mix of the above answer and what i saw in the documentation:

    let fileDataA4 = fs.readFileSync('path/to/A4.mp3');
    
    // create a Tone.js Player connected to the audio output
    const player = new Tone.Player().toDestination();
    
    let arrayBufferA4 = await new Blob([fileDataA4]).arrayBuffer();
    
    // create a ToneAudioBuffer from the ArrayBuffer with loaded buffer
    const bufferA4 = await player.context.decodeAudioData(arrayBufferA4);
                    
    
    let fileDataA5 = fs.readFileSync("path/to/A5.mp3");
    
    let arrayBufferA5 = await new Blob([fileDataA5]).arrayBuffer();
    
    const bufferA5 = await player.context.decodeAudioData(arrayBufferA5);
                    
    let sampler = new Tone.Sampler({
            urls: {
                "A4" : bufferA4,
                "A5" : bufferA5
            }
    }).toDestination();
                    
    Tone.loaded().then(() => {
        sampler.triggerAttackRelease("C4", "1n")
    })
    

    This way, you only need to load 2 mp3 files, the sampler does the rest for you