DOMException when playing audio with blob as source

后端 未结 2 1446
失恋的感觉
失恋的感觉 2021-01-28 17:06

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 =&g         


        
2条回答
  •  [愿得一人]
    2021-01-28 17:45

    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.

提交回复
热议问题