我正在尝试将音频数据从网页上传到服务器,并发现它比原本应该的困难。
这是我的测试页,它带有一个按钮,单击该按钮时,将开始录制5秒钟的声音,然后播放该声音,最后将声音数据上传到服务器。
声音录制和播放部分工作正常。 上传到服务器不能完全正常工作。
我的代码在下面完全可见。我故意放了整个文件(称为“ GetAudio.php”),所以任何人都可以轻松地将其粘贴粘贴以进行尝试。
出了什么问题:在服务器上创建的名为“ Audio.data”的文件包含4个字符,即:
blob
这不是我想要的。我希望文件包含本地记录的实际声音数据。有人可以告诉我我的代码在哪里缺少一些重要的东西吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Record&Upload Trial</title>
</head>
<body>
<div>
<h2>Five seconds voice record and upload.</h2>
<p>
<button id=startRecord><h3>Start the voice recording</h3></button><br/>
<audio id="player" controls></audio>
<p id="XMLH"></p>
</p>
</div>
<?php
// Server side code:
if ($_POST['AudioData']) {
$myfile = fopen("Audio.data", "w");
fwrite($myfile, $_POST['AudioData']);
fclose($myfile);
}
?>
<script>
startRecord.onclick = e => {
startRecord.disabled = true;
audioChunks = [];
rec.start();
setTimeout(() => {
rec.stop();
startRecord.disabled = false;
}, 5000);
}
var player = document.getElementById('player');
var handleSuccess = function(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
player.src = URL.createObjectURL(blob);
player.controls=true;
player.autoplay=true;
// The code below intends to upload the sound file to the server.
// But it is partly (or completely) wrong and does not work.
var xhr = new XMLHttpRequest();
var params = 'AudioData=blob';
xhr.open('POST', 'GetAudio.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
}
};
navigator.mediaDevices.getUserMedia({audio:true})
.then(handleSuccess);
</script>
</body>
</html>