在html5中播放来自bytearray的音乐 [英] Play music from bytearray in html5

查看:227
本文介绍了在html5中播放来自bytearray的音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以从字节中播放音乐,而不是HTML 5中的文件?



我需要传送音乐字节并实时播放。

解决方案

请检查这个

  var dogBarkingBuffer = null; 
//修正前缀
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();

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

//异步解码
request.onload = function(){
context.decodeAudioData(request.response,function(buffer){
dogBarkingBuffer = buffer;
},onError);
}
request.send();





音频文件数据是二进制文件(不是文本),所以我们设置responseType对'arraybuffer'的请求。有关ArrayBuffers的更多信息,请参阅这篇关于XHR2的文章。



一旦接收到(未解码)音频文件数据,它可以保留以供稍后解码,可以使用AudioContext decodeAudioData()方法立即解码。这个方法使用request.response中存储的音频文件数据的ArrayBuffer并异步解码(不阻塞主JavaScript执行线程)。

当decodeAudioData()完成时,它调用一个回调函数,将解码后的PCM音频数据作为AudioBuffer提供。

和这里的引用==> HML5音频



更新:
让它适用于Firefox和chrome的使用:


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

而不是:

  var context = new AudioContext(); 


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.

解决方案

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

这篇关于在html5中播放来自bytearray的音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆