jQuery $.ajax 或 $.load 是否允许 responseType arrayBuffer?

2022-01-15 00:00:00 xmlhttprequest jquery ajax

我开始使用 Web Audio API,只是想知道是否可以使用 jQuery 的 $.ajax 或 $.load 函数来生成接收音频数据的 XMLHttpRequest.$.ajax 或 $.load 是否支持 responseType=arrayBuffer?

I'm getting started with the Web Audio API and just wondering if it's possible to use jQuery's $.ajax or $.load functions to make the XMLHttpRequest that receives the audio data. Do $.ajax or $.load support responseType=arrayBuffer?

好的,这就是我目前所拥有的:

Ok, so here's what I have so far:

function loadAudio() {
    $.ajax({
            url: sourceUrl
        }).done(function(response){
            return response;
        })
    }

但我需要返回一个 ArrayBuffer.那么如何将响应转换为 ArrayBuffer 呢?

but I need to return an ArrayBuffer. So how do I convert the response into an ArrayBuffer?

推荐答案

关于你的问题,jQuery 好像还不支持.在按照我下面的建议使用它之前,请考虑检查该功能是否可用.

About your question, it seems jQuery does not support it yet. Before using it as I suggested below, consider checking if the feature is available.

使用 XHTMLRequest,您可以欺骗您的服务器并从服务器接收表示您想要的字节的二进制字符串.效果很好.

With XHTMLRequest, you can trick your server and receive a binary string representing the bytes you want from the server. It works perfectly.

var xhr = new XMLHttpRequest();
xhr.open('GET', '/your/audio/file.wav', true);

// Here is the hack
xhr.overrideMimeType('text/plain; charset=x-user-defined');

xhr.onreadystatechange = function(event) {
  if ( this.readyState == 4 && this.status == 200 ) {
    var binaryString = this.responseText;

    for (var i = 0, len = binaryString.length; i < len; ++i) {
      var c = binaryString.charCodeAt(i);
      var byte = c & 0xff; //it gives you the byte at i
      //Do your cool stuff...

    }
  }
};

xhr.send();

它有效,它很常见......但是......它仍然是一个黑客.

It works, it's common... but... it is still a hack.

使用 XHTML 请求级别 2,您可以将 responseType 指定为 'arraybuffer' 并实际接收 ArrayBuffer.它要好得多.问题是检查您的浏览器是否支持此功能.

With XHTML Request Level 2, you can specify the responseType as 'arraybuffer' and receive the ArrayBuffer actually. It is much nicer. The problem is to check if your browser support this feature.

var xhr = new XMLHttpRequest();
xhr.open('GET', '/your/audio/file.wav', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  if (this.status == 200) {
    //Do your stuff here
  }
};

xhr.send();

希望我能帮上忙.

相关文章