【问题标题】:Play music from bytearray in html5在 html5 中播放来自 bytearray 的音乐
【发布时间】:2013-06-12 05:36:07
【问题描述】:

在 HTML 5 中有没有办法从字节而不是文件播放音乐?

我需要流式传输音乐字节并现场播放。

【问题讨论】:

  • html5 音频可以播放流,它可以在 icecast 服务器上正常工作

标签: html xmlhttprequest html5-audio


【解决方案1】:

请检查一下

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

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

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

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

这里是参考 ==> HML5 audio

更新: 让它在 Firefox 和 chrome 上运行:

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

而不是:

var context = new AudioContext();

【讨论】:

  • 只适用于谷歌浏览器!?
猜你喜欢
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多