Play music from bytearray in html5

老子叫甜甜 提交于 2019-12-04 19:50:43

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/17127639/play-music-from-bytearray-in-html5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!