How can I get audio file from XMLHttpRequest that can be decoded by decodeAudioData?

梦想与她 提交于 2019-12-24 23:42:43

问题


I want to replay an audio file from a server in JavaScript, but I cannot get the correct data format for decodeAudioData to decode it.

Here is my method for getting and playing the audio data in JavaScript:

  var source = audioContext.createBufferSource();
  var request = new XMLHttpRequest();
  request.open('GET', 'https://audioserver.com/getaudio.php', true);
  request.responseType = 'arraybuffer';

  request.onload = function() {
    var audioData = request.response;
    audioContext.decodeAudioData(audioData, function(buffer) {
        source.buffer = buffer;
        source.connect(audioContext.destination);
        source.loop = true;
      },
      function(e){"Error with decoding audio data" + e.err});
    source.start(0);
  }
  request.send();

My server code looks like this:

<?php
    header('Access-Control-Allow-Origin: *');
    $file = "audiofiles/audio.wav";
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
?>

And I also tried this:

<?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;
?>

But both of the above approaches lead to the following error in JavaScript:

DOMException: Unable to decode audio data

How can I get the audio file in JavaScript correctly so that it can be decoded and replayed correctly?

来源:https://stackoverflow.com/questions/36093768/how-can-i-get-audio-file-from-xmlhttprequest-that-can-be-decoded-by-decodeaudiod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!