bobby_z
bobby_z

Reputation: 47

Fail to read audio from blob url in mobile Chrome

I want to use mp3 playing in my mobile web app, so I wrote a test app, I used this solution but blob URL seems to be broken and empty while file is rightly readed.

<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 size is wrong, I've put bigger file Blob size is wrong

EDIT:

I used older version with FileReader, maybe this is not good choice but it works...

Upvotes: 0

Views: 1272

Answers (1)

Endless
Endless

Reputation: 37806

Don't use decodeURIComponent just do 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">

btw, I get problem playing it directly, it's weird since the event.isTrusted is true, that's why i appended the audio to the DOM

Upvotes: 1

Related Questions