编程语言
首页 > 编程语言> > javascript – XMLHttpRequest和http流

javascript – XMLHttpRequest和http流

作者:互联网

我的目标是从浏览器读取HTTP MP3音频流并访问原始音频数据.

> HTML5<音频>让我轻松播放流,但据我所知,不允许访问原始音频数据.它只是播放它.
> JS XMLHTTPRequest可以通过HTTP下载文件并处理原始音频数据.它似乎是一个很好的候选者,但它受到限制:它不会授权访问二进制数据,直到下载完成(readystate = 4).在我的例子中,流是无限的,因此readystate永久保持在3并且XHR响应为空(这种行为在mozilla文档中有详细说明).请注意,我连接的服务器的跨源策略是Access-Control-Allow-Origin:*

代码示例适用于本地常规文件,但不适用于流.我在request.response.length上得到一个空指针异常

request = new XMLHttpRequest();
//request.open('GET', 'test.mp3', true);
request.open('GET', 'http://domain.com/stream.mp3', true);
request.responseType = 'arraybuffer';
request.onload = function() {
  console.log("request onl oad");
  var audioData = request.response;
  audioCtx.decodeAudioData(audioData, 
    function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, 
    function(e){"Error with decoding audio data" + e.err}
  );
}
request.onreadystatechange = function() {
    console.log("ready state = " + request.readyState);
    console.log(request.response.length);
}
request.send();

有没有人知道这些选项的替代方案或变通方法,以便在下载流时可以读取原始二进制数据包?

请注意,我无法控制服务器.这是一个icecast http流.
此外,在浏览器方面,我想避免使用Flash.
谢谢

编辑:为了澄清可能的跨源问题,JS在托管在localhost服务器上的页面上运行.

解决方法:

以下解决方法有效:

如MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data中所述,可以覆盖http请求的MIME类型,将其设置为自定义,并调用responseText.

function load_binary_resource(url) {
  var req = new XMLHttpRequest();
  req.open('GET', url, false);
  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null);
  if (req.status != 200) return '';
  return req.responseText;
} 

关键是req.responseText没有受到req.response的相同限制.它在readystate = 3状态下不为null.
然后,访问二进制responseText

var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)

一个重要的缺点是req.responseText在下载流时不断增长.应该不时重置请求以避免过多的RAM消耗.

标签:javascript,html5,audio,xmlhttprequest,icecast
来源: https://codeday.me/bug/20190829/1762783.html