首页 > 解决方案 > 无法从移动 Chrome 中的 blob url 读取音频

问题描述

我想在我的移动网络应用程序中使用 mp3 播放,所以我编写了一个测试应用程序,我使用了这个解决方案,但是当文件被正确读取时,blob URL 似乎被破坏并且为空。

<input type="file" accept=".mp3" onchange="autoplay()">
<script>
    var file, url, audio, source;
function autoplay(){
    window.URL = window.URL || window.webkitURL;
    file = document.querySelector("input[type=file]").files[0];
    url = decodeURIComponent(window.URL.createObjectURL(file));
    audio = document.createElement("audio");
    source = document.createElement("source");
    source.src = url;
    audio.appendChild(source);
    document.body.appendChild(audio);
    audio.play();
}
</script>

Blob 大小错误,我放了更大的文件 Blob 大小错误

编辑:

我在 FileReader 中使用了旧版本,也许这不是一个好的选择,但它可以工作......

标签: javascripthtmlaudioblob

解决方案


不要使用decodeURIComponent只是做URL.createObjectURL

window.URL = window.URL || window.webkitURL;

function autoplay(evt) {
  var file = document.querySelector("input[type=file]").files[0];
  var url = URL.createObjectURL(file);
  var audio = new Audio();
  audio.src = url;
  audio.play().catch(function(err){
    console.error(err) // could not play audio
  });
  audio.controls = true;
  document.body.appendChild(audio);
}

document.querySelector("input[type=file]").onchange = autoplay
<input type="file" accept=".mp3">

顺便说一句,我直接播放时遇到问题,这很奇怪,因为这event.isTrusted是真的,这就是我将音频附加到 DOM 的原因


推荐阅读