<button id="recordButton">开始录制</button>
let recordButton = document.getElementById('recordButton');
let mediaRecorder; //媒体实例
let chunks = [];//语音文件
let isRecording = false;//是正在录制还是停止录制
recordButton.addEventListener('click', () => {
if (!isRecording) {
chunks = []; // 清空数组
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.ondataavailable = (e) => {
chunks.push(e.data);
};
mediaRecorder.onstop = (e) => {
let blob = new Blob(chunks, { 'type' : 'audio/wav' });
// 创建一个 FormData 对象
let formData = new FormData();
// 添加录音文件
formData.append('audio_file', blob, 'audio.wav');
// 使用 fetch API 发送录音文件
// url 为请求的路径
const response = fetch(url, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
};
})
.catch(err => console.log('Error: ', err));
recordButton.textContent = '结束录制';
isRecording = true;
} else {
mediaRecorder.stop();
recordButton.textContent = '开始录制';
isRecording = false;
}
});
同理,上传文件给后台原理相同。
标签:mediaRecorder,recordButton,isRecording,JS,chunks,let,后台,wav From: https://www.cnblogs.com/guorh666/p/17519595.html