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

0

Issue

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.
});

Answered By – Emiel Zuurbier

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More