问题
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