JavaScript - 如何将音频文件加载到readAsArrayBuffer中?

3

我遇到了一些问题,无法加载音频文件并将其放入 readAsArrayBuffer 中。我不想让用户选择文件,我只想本地加载一个文件,像这样:

let file = new File('../music/song.mp3');
let reader = new FileReader();

reader.onload = function(e) {
    playSound(e.target.result);
}
reader.readAsArrayBuffer(file);

当我执行以上操作时,出现以下错误:
Uncaught TypeError: Failed to construct 'File': 2 arguments required, but only 1 present.
因此我尝试了这个方法:
let file = new File([''], '../music/song.mp3');

然后就会出现这个错误:

未捕获(在承诺中)DOM异常:无法解码音频数据

我相信它加载的大小为0,这就是为什么会出现这个错误。

当我让用户选择要加载的文件时,一切都正常:

document.getElementById('open-file').onchange = function(evt) {
    let file = evt.target.files[0];

有人知道如何修复这个问题吗?


1
你不能在没有用户交互的情况下读取本地文件系统文件,否则会存在安全风险。另请参阅File()文档,它显示了它所需的参数。 - Patrick Evans
1
你需要获取这个文件,File构造函数不能处理它,也不接受URI作为输入。所以你想要的是fetch('../music/song.mp3').then(r=>r.arrayBuffer()).then(buf=>audioContext.decodeAudioData(buf).then(enjoyTheAudioBuffer); - Kaiido
2个回答

0

这使用fetch加载一个文件,并立即使用Audio Web API播放它。当然,你可以将其放入一个函数中并调用它来随时播放。

是否有什么阻止它或使其不可取的因素?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minimal Audio Example</title>
</head>
<body>
    <h1>Audio should play right away</h1>
    <p>You will need to add the audio example, though.</p>
</body>
<script type="module">
    const audioFileResponse = await fetch('./example-audio.mp3')
    const arrayBuffer = await audioFileResponse.arrayBuffer()
    const audioContext = new AudioContext();
    const audioBuffer = await audioContext.decodeAudioData(arrayBuffer)
    const source = audioContext.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(audioContext.destination);
    source.start();
</script>
</html>


0
正如Patrick Evans所述,由于安全风险,这是不可能的。这真是太遗憾了,因为你可以很容易地使用HTML5播放音频,但你无法将音频文件加载并读取为数组缓冲区。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接