简体   繁体   English

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

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

I want to get an audio file from a server in JavaScript and play it. 我想从服务器中使用JavaScript获取音频文件并播放。 But the ajax call in my code never seems to callback, and I am also unsure whether I handle the audio in JavaScript correctly. 但是我代码中的ajax调用似乎从未回调过,并且我也不确定我是否正确处理了JavaScript中的音频。

The following PHP file returns the audio file on the server: 以下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;
?>

The script is called from JavaScript using ajax and the returned audio data is replayed in the browser (at least thats what should happen): 使用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);
    }
  });
}

What am I doing wrong here? 我在这里做错了什么?

jQuery ajax does not support typed responses, so you're going to get text as result in your success callback. jQuery ajax不支持类型化的响应,因此您将获得文本作为成功回调的结果。

You can use bare XMLHTTPRequest to get a binary response 您可以使用裸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();      

There is also a plugin that patches jquery to support it https://github.com/acigna/jquery-ajax-native 还有一个插件可以修补jquery以支持它https://github.com/acigna/jquery-ajax-native

Also your your audio processing code looks incorrect. 另外,您的音频处理代码看起来也不正确。 buffers[0] doesn't make sense since an arraybuffer doesn't have numeric properties buffers[0]没有意义,因为arraybuffer没有数值属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM