2

再次需要帮助

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

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

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

而最终的目标是获取audioBuffer

谢谢你的任何答案

4

1 回答 1

2

使用 Fetch API 从服务器请求文件。然后将其读取为an并使用该方法ArrayBuffer将其解码为an 。AudioBufferBaseAudioContext.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.
});
于 2021-12-25T23:01:53.900 回答