我想用 JavaScript 从服务器获取音频文件并播放它。但是我的代码中的 ajax 调用似乎永远不会回调,我也不确定我是否正确处理了 JavaScript 中的音频。
以下 PHP 文件返回服务器上的音频文件:
<?php
header('Access-Control-Allow-Origin: *');
$name = './audiofiles/audio.wav';
$fp = fopen($name, 'rb');
header("Content-Type: binary");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
?>
该脚本使用 ajax 从 JavaScript 调用,返回的音频数据在浏览器中重播(至少应该发生这种情况):
function playSample(e,q) {
console.log("requesting audio from server")
$.ajax({
url: "https://audioserver.com/getaudio.php",
type: "GET",
dataType: "arraybuffer",
processData: false,
success: function(result){
console.log("received audio, starting to play now")
var buffers = result;
var newSource = audioContext.createBufferSource();
var newBuffer = audioContext.createBuffer( 2, buffers[0].length, 16000 );
newBuffer.getChannelData(0).set(buffers[0]);
newSource.buffer = newBuffer;
newSource.connect( audioContext.destination );
newSource.start(0);
}
});
}
我在这里做错了什么?
最佳答案
jQuery ajax 不支持类型化响应,因此您将在成功回调中获得文本作为结果。
您可以使用纯 XMLHTTPRequest 来获取二进制响应
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is the array buffer for you to manipulate
}
}
xhr.open('GET', 'https://audioserver.com/getaudio.php');
xhr.responseType = 'arraybuffer';
xhr.send();
还有一个插件可以修补 jquery 以支持它 https://github.com/acigna/jquery-ajax-native
您的音频处理代码看起来也不正确。 buffers[0]
没有意义,因为 arraybuffer 没有数字属性
关于javascript - 如何在 JavaScript ajax 调用中从 PHP passthru 获取二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36092850/