Play MP3 file stored as blob

Axel picture Axel · Oct 22, 2012 · Viewed 22.5k times · Source

Put simply, I'd like to play a blob MP3 file in Firefox.

I have access to both the blob itself: blob (sliced with mime type audio/mpeg3), and its URL: blobURL = window.URL.createObjectURL(blob).

I have tried with:

  1. an HTML5 audio player:

    <audio controls="controls">
        <source src="[blobURL]" type="audio/mp3">
    </audio>
    

    but I get a warning in Firebug telling me that Firefox cannot read files of type audio/mpeg3.

  2. multiple audio player libraries (SoundManager, JPlayer, etc.), but none seem to allow blob URLs as input.

Am I doing it wrong? Or does anyone know a workaround or a library that can play MP3 files from blobs?

Answer

CodingIntrigue picture CodingIntrigue · Feb 25, 2014

This seems to work fine for me, although I'm using audio/mpeg as the MIME Type:

$scope.player = new window.Audio();

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        $scope.player.src = window.URL.createObjectURL(this.response);
        $scope.player.play();
    }
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();