使用反应时访问“本地”文件以在 Web 音频 API 中使用的最佳方式?

Posted

技术标签:

【中文标题】使用反应时访问“本地”文件以在 Web 音频 API 中使用的最佳方式?【英文标题】:Best way to access 'local' files to use in Web Audio API when using react? 【发布时间】:2020-11-09 00:09:36 【问题描述】:

我正在研究一种低延迟“onClick”声音的方法。我有一个 .wav 文件,我想用 audioBufferNode 播放。但是,我熟悉将 .wav 处理为音频缓冲区的唯一方法是使用 fetch() 我尝试将文件存储在我的 create-react-app 初始化项目的 /public 目录中,但这似乎在错误之后抛出错误。

这里有什么我遗漏的吗?当该文件是反应应用程序的资产时,加载音频文件并将其处理到音频缓冲区的最佳方法是什么。能不能先导入再以某种方式处理?

【问题讨论】:

【参考方案1】:

使用fetch() 获取文件并将它们解码为AudioBuffer,以便通过Web Audio API 播放。我建议使用像 Opus 或 MP3 这样的小型压缩文件,而不是大型的原始 WAV 文件。使用opusenc 对您的文件进行编码。 96kb/s 质量/大小最佳点 (hear comparison)。

const audioCtx =  new (window.AudioContext || window.webkitAudioContext)( latencyHint: 'playback' )
const $ = document.querySelector.bind(document)

initSound(
  'https://batman.dev/static/61881209/50.opus',
  $('#sound1')
)
initSound(
  'https://batman.dev/static/61881209/99.opus',
  $('#sound2')
)

function initSound(url, playbackButton) 
  fetch(url)
  .then(resp => resp.arrayBuffer())
  .then(arrayBuffer => audioCtx.decodeAudioData(arrayBuffer))
  .then(audioBuffer => 
    playbackButton.onclick = () => playSound(audioBuffer)
    playbackButton.disabled = false 
  )    


function playSound(audioBuffer) 
  const bufferSource = audioCtx.createBufferSource()
  bufferSource.buffer = audioBuffer;
  bufferSource.connect(audioCtx.destination);
  bufferSource.start(0);  
html  background: #181e2d; padding: 1rem; 
button  padding: 1em 2em; color: #999; border: none; 
button:enabled  color: #fff; background: #0095ff; cursor: pointer; 
<button id="sound1" disabled>▶  Snap</button>
<button id="sound2" disabled>▶  Hey!</button>

【讨论】:

以上是关于使用反应时访问“本地”文件以在 Web 音频 API 中使用的最佳方式?的主要内容,如果未能解决你的问题,请参考以下文章