简体   繁体   English

将 wav 文件的 ArrayBuffer 转换为 Blob

[英]Convert ArrayBuffer of wav file to Blob

I'm trying to fetch from the server an audio wav file , and play it in the client with the element.我正在尝试从服务器获取音频 wav 文件,并使用该元素在客户端中播放它。

<audio id="recording" src="..." />`

I got the data as ArrayBuffer, and im trying to convert it to blob so I can change the src of the element我将数据作为 ArrayBuffer 获取,并尝试将其转换为 blob,以便更改元素的 src

This is the code:这是代码:

fetch("http://localhost:8080/", requestOptions)
    .then( (response) => {
        return response.arrayBuffer()
    }).then( (data) => {
        let a = new Blob([data], {type : 'audio/wav'});
        document.getElementById("recording").src = a;
    })
    .catch(error => console.error( error));

But there is an error:但是有一个错误:

GET chrome-extension://goohbjdkcejkkochpdellmjkkdpfngph/[object%20Blob] net::ERR_FILE_NOT_FOUND

It seams I didn't create the Blob properly看起来我没有正确创建 Blob

How can I create the blob and pass it to the <audio... /> element?如何创建 blob 并将其传递给<audio... />元素?

You have to create an actual URL from your blob.您必须从您的 blob 创建一个实际的 URL。 And don't forget to revoke it afterward to free the resources.并且不要忘记事后撤销它以释放资源。

let blob = new Blob([data], {type : 'audio/wav'});
const url = URL.createObjectURL(blob);
document.getElementById("recording").src = url;
URL.revokeObjectURL(url);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM