我正在尝试使用电子反应样板创建一个应用程序,我可以在其中创建音频文件。
我找到了 Tone.js,它允许我播放声音,但加载示例文件似乎几乎是不可能的。有没有办法把音频数据交给Tone?
我正在使用 Sampler,但我不知道如何创建 URL 来传输数据
Player.load
的实现,它可以处理 ArrayBuffer,幸运的是,使用 <input type="file">
可以通过 FileReader 获取 ArrayBuffer
这里是一些示例代码,假设您的 HTML 中有一个 id 为“local-file”的文件输入,并且此时您已经加载了 Tone.js:
document.querySelector('#local-file').addEventListener('change', async function() {
await Tone.start();
// create a FileReader to process the chosen file
const fileReader = new FileReader();
// when it's read into an ArrayBuffer, we can access that in the result property of the event target
fileReader.onload = async (event) => {
// create a Tone.js Player connected to the audio output
const player = new Tone.Player().toDestination();
// create a ToneAudioBuffer from the ArrayBuffer with file contents. event.target.result is the ArrayBuffer with the file content
const buffer = await player.context.decodeAudioData(event.target.result);
// add the buffer to our player
player.buffer = buffer;
// once we're ready, start the player.
Tone.loaded().then(() => {
player.start();
});
}
// read the selected file into an ArrayBuffer
fileReader.readAsArrayBuffer(this.files[0]);
});