DOMException when playing audio with blob as sourc

2020-04-30 18:02发布

Whenever I run this code

var blob = new Blob(["ninja.mp3"], {type:"audio/mp3"});
var audio = new Audio(URL.createObjectURL(blob));
audio.play().catch(err => console.log(err));

I am given the following error

DOMException index.html:3

I expect it to play the audio file ninja.mp3 but instead I'm faced with this error. Any help would be greatly appreciated.

2条回答
叛逆
2楼-- · 2020-04-30 18:35

When you do

var blob = new Blob(["ninja.mp3"], {type:"audio/mp3"});

What you just created is a Binary file in your browser's memory which holds the USVString ninja.mp3, and for which the browser will send a Content-Type: audio/mp3 header in some network actions.

Id est, you just created an UTF-8 text file. And yes, the MediaElement is not able to read that.

var blob = new Blob(["ninja.mp3"], {type:"audio/mp3"});
// read as text
new Response(blob).text().then(console.log);

For a comparison, here is what a real mp3 file looks like when read as text:

fetch("https://dl.dropboxusercontent.com/s/agepbh2agnduknz/camera.mp3")
 .then(resp => resp.text())
 .then(console.log)

Blob constructor doesn't expect an URL, but a list of Blob parts (which are either USVStrings, Blobs or ArrayBuffers), but in no way will it ever fetch anything.

So what you want seems to be as simple as

var audio = new Audio("ninja.mp3");
audio.play().catch(console.log);

But if one day you need to build a Blob (which you don't now), then be sure that what you pass in the Blob() constructor is actually the binary content of your file.

查看更多
家丑人穷心不美
3楼-- · 2020-04-30 18:57

The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. This is basically how error conditions are described in web APIs.

I think you call the method wrongly. Pls Check it.

查看更多
登录 后发表回答