Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play music from bytearray in html5

Is there any way to play music from bytes instead of a file in HTML 5?

I need to stream music bytes and play them live.

like image 456
Ata Avatar asked Jun 15 '13 20:06

Ata


1 Answers

please check this

  var dogBarkingBuffer = null;
 // Fix up prefixing
 window.AudioContext = window.AudioContext || window.webkitAudioContext;
 var context = new AudioContext();

function loadDogSound(url) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'arraybuffer';

  // Decode asynchronously
  request.onload = function() {
    context.decodeAudioData(request.response, function(buffer) {
      dogBarkingBuffer = buffer;
    }, onError);
  }
  request.send();
}

The audio file data is binary (not text), so we set the responseType of the request to 'arraybuffer'. For more information about ArrayBuffers, see this article about XHR2.

Once the (undecoded) audio file data has been received, it can be kept around for later decoding, or it can be decoded right away using the AudioContext decodeAudioData() method. This method takes the ArrayBuffer of audio file data stored in request.response and decodes it asynchronously (not blocking the main JavaScript execution thread).

When decodeAudioData() is finished, it calls a callback function which provides the decoded PCM audio data as an AudioBuffer.

and here the reference ==> HML5 audio

UPDATE: to let it work on Firefox and chrome use:

context= typeof AudioContext !== 'undefined' ? new AudioContext() : new webkitAudioContext();

instead of :

var context = new AudioContext();
like image 112
Muath Avatar answered Nov 11 '22 02:11

Muath