如何从XMLHttpRequest获取可由decodeAudioData解码的音频文件?

时间:2016-03-18 20:35:32

标签: javascript php audio xmlhttprequest

我想用JavaScript重播服务器上的音频文件,但我无法获得decodeAudioData的正确数据格式来解码它。

以下是我在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();

我的服务器代码如下所示:

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

我也试过这个:

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

但是上述两种方法都会导致JavaScript中出现以下错误:

  

DOMException:无法解码音频数据

如何正确地使用JavaScript获取音频文件,以便正确解码和重放?

0 个答案:

没有答案