如何在 JavaScript ajax 调用中从 PHP 传递中获取二进制数据


How can I get binary data from PHP passthru in JavaScript ajax call?

我想从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]没有意义,因为数组缓冲区没有数字属性