参考错误:AudioBuffer 未定义

问题描述

我正在尝试在 next.js react 项目中使用tone.js。 当我运行或构建时,我收到此错误“ReferenceError: AudioBuffer is not defined”

我已经在 codeandBox 中隔离了tone.js 代码并且它运行良好。 https://codesandbox.io/s/tonejs-react-pink-noise-generator-pfnl0?file=/src/App.js

但不是在 next.js 应用程序中

ReferenceError: AudioBuffer is not defined
    at ki (/node_modules/tone/build/Tone.js:1:117922)```

解决方法

AudioBuffer 是网络浏览器的东西,它在 node.js 中不存在。您收到的错误是因为使用 AudioBuffer 的代码无法在服务器上运行。您只需要在浏览器中实例化那部分代码。这通常在 useEffect 钩子中完成,或者在服务器上,您可以先检查是否定义了 window 对象。