javascriptnode.jsblobaudiobuffer

How to create Blob from local file with require in NodeJS?


need help again

I use Webpack and I have audio file, this is how I load it:

const file = require('@/assets/filename.mp3')
const blob = new Blob(file) // it doesn't work

Now I need to get Blob from it.. I can't understand how to do that.

And the final goal is to get audioBuffer

Thank you for any answers 🙏


Solution

  • Use the Fetch API to request the file from the server. Then read it as an ArrayBuffer and decode it to an AudioBuffer by using the BaseAudioContext.decodeAudioData() method.

    /**
     * Get a file, read it as an ArrayBuffer and decode it an AudioBuffer.
     * @param {string} file
     * @returns {Promise<AudioBuffer>}
     */
    const fetchAudioBuffer = async file => {
      const audioContext = new AudioContext();
    
      try {
        const response = await fetch(file);
        const arrayBuffer = await response.arrayBuffer();
        return audioContext.decodeAudioData(arrayBuffer);
      } catch (error) {
        console.error(error);
      }
    };
    
    // Fetch the file and decode it as an AudioBuffer.
    fetchAudioBuffer('path/to/assets/filename.mp3').then(audioBuffer => {
      // Use your audioBuffer here.
    });