下面是一个使用JavaScript录制音频并将其上传到服务器的示例代码:
HTML部分:
<input type="button" value="开始录音" onclick="startRecording()" />
<input type="button" value="停止录音" onclick="stopRecording()" />
<audio id="recordedAudio" controls></audio>
JavaScript部分:
var mediaRecorder;
var recordedChunks = [];
function startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.addEventListener("dataavailable", function(e) {
recordedChunks.push(e.data);
});
});
}
function stopRecording() {
mediaRecorder.stop();
mediaRecorder.addEventListener("stop", function() {
var blob = new Blob(recordedChunks, { type: "audio/webm" });
var url = URL.createObjectURL(blob);
document.getElementById("recordedAudio").src = url;
uploadAudio(blob);
});
}
function uploadAudio(blob) {
var formData = new FormData();
formData.append("audio", blob, "recording.webm");
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Audio uploaded successfully");
}
};
xhr.send(formData);
}
PHP部分(upload.php):
<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["audio"]["name"]);
move_uploaded_file($_FILES["audio"]["tmp_name"], $targetFile);
?>
请确保在服务器上创建一个名为"uploads"的文件夹,用于存储上传的音频文件。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站