如何在 NodeJS 中使用 require 从本地文件创建 Blob?

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

再次需要帮助

我使用 Webpack 并且我有音频文件,这是我加载它的方式:

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

现在我需要从中获取 Blob。我不明白该怎么做。

而最终的目标是获取audioBuffer

感谢您的任何回答

使用 Fetch API 从服务器请求文件。然后将其作为 ArrayBuffer and decode it to an AudioBuffer by using the BaseAudioContext.decodeAudioData() 方法读取。

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