4

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 🙏

1
  • 1
    Unfortunately it doesn't work like that. You'll need to fetch the MP3 file from the server with AJAX. Commented Dec 25, 2021 at 22:47

1 Answer 1

2

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.
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.