使用本地文件动态设置音频源

Set audio src using local file dynamically

Firefox 中,我正在尝试从用户的文件系统加载音频文件。
我读过我可以根据路径 here
创建一个 File 对象 该代码将 运行 在 firefox 插件中,因此可以访问特权代码。

知道为什么这会导致控制台出错以及 document.getElementById('player') 元素消失吗?

http://jsfiddle.net/bobbyrne01/sp5qr7hh/

^ fiddle 仅用于演示目的,它最终会 运行 在 firefox 插件中。

html ..

<audio id="player" preload="auto" controls></audio>

js ..

var reader = new FileReader();
reader.onload = function(d) {
    console.log(d.target.result);
    document.getElementById('player').src = d.target.result;
};
reader.readAsDataURL(new File([""], "file:///home/rob/audio.mp3"));

控制台输出..

"data:application/octet-stream;base64," _display:24
HTTP "Content-Type" of "application/octet-stream" is not supported. Load of media resource data:application/octet-stream;base64, failed.

filesystem ..

rob@work:~$ pwd
/home/rob
rob@work:~$ ls audio.mp3 
audio.mp3

您是否为 <audio> 标签使用推荐的 HTML5 DOM 结构,它应该有效:

var sourceElem = document.createElement('source');
sourceElem.setAttribute('src', "file:///home/rob/audio.mp3");
document.getElementById('player').appendChild(sourceElem);

我得到 jsfiddle 给我一个安全错误,说它不应该加载本地资源。

通过远程网站加载本地文件是一个安全问题。您还必须检测用户使用的系统以获得正确的文件结构。大多数浏览器会阻止这种行为,因为您不应该能够读取用户计算机上的任何随机文件,除非他们将其放入上传表单中。

您的用户基本上必须从本地副本 运行 您的网站(类似于 iOS 上的本地网络应用程序)