【问题标题】:Fail to read audio from blob url in mobile Chrome无法从移动 Chrome 中的 blob url 读取音频
【发布时间】:2019-01-22 13:46:45
【问题描述】:

我想在我的移动网络应用程序中使用 mp3 播放,所以我编写了一个测试应用程序,我使用了 this 解决方案,但在正确读取文件时,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 大小错误,我放了更大的文件

编辑:

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

【问题讨论】:

    标签: javascript html audio blob


    【解决方案1】:

    不要使用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
    &lt;input type="file" accept=".mp3"&gt;

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

    【讨论】:

    • 谢谢,我在没有 decodeURIComponent 的情况下使用它,但我遇到了同样的问题 - 文件只是空的,然后我决定使用 FileReader - 它可以工作,但文件较大时会导致移动浏览器崩溃
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    相关资源
    最近更新 更多