问题描述
每当我运行此代码时
var blob = new Blob(["ninja.mp3"], {type:"audio/mp3"});
var audio = new Audio(URL.createObjectURL(blob));
audio.play().catch(err => console.log(err));
我收到以下错误
DOMException index.html:3
我希望它可以播放音频文件 ninja.mp3
但我遇到了这个错误。任何帮助将不胜感激。
I expect it to play the audio file ninja.mp3
but instead I'm faced with this error. Any help would be greatly appreciated.
推荐答案
当你这样做时
var blob = new Blob(["ninja.mp3"], {type:"audio/mp3"});
您刚刚创建的是浏览器内存中的二进制文件,其中包含USVString ninja.mp3
,浏览器将在某些网络操作中发送 Content-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 ,您刚刚创建了一个UTF-8文本文件。是的,MediaElement无法读取。
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);
为了进行比较,这是一个真实的mp3文件,当作为文本阅读时是什么样的:
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构造函数不期望一个URL,而是一个Blob部分列表(USVStrings,Blob或ArrayBuffers),但绝不会取任何东西。
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);
但是如果有一天你需要建立一个Blob(你现在没有),那么确保您在Blob()构造函数中传递的内容实际上是文件的二进制内容。
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.
这篇关于使用blob作为源播放音频时出现DOMException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!