問題描述
我開始使用 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();
希望我能幫上忙.
這篇關于jQuery $.ajax 或 $.load 是否允許 responseType arrayBuffer?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!