Bootstrap

LLM(3) : 浏览器录制16K的音频并上传到后端

可被阿里云[qwen-audio-asr]大模型识别 

 HTML

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>录音并上传</title>
	</head>
	<body>

		<button id="recordButton">开始/停止录音</button>
		<audio id="audioPlayback" controls style="display:none;"></audio>

		<script>
			let mediaRecorder;
			let audioChunks = [];
			let recording = false;

			document.getElementById('recordButton').addEventListener('click', () => {
				if (recording) {
					// 停止录音
					stopRecording();
				} else {
					// 开始录音
					startRecording();
				}
			});

			async function startRecording() {
				try {
					const stream = await navigator.mediaDevices.getUserMedia({
						audio: true
					});

					// 创建 MediaRecorder 实例,但不连接到任何音频输出
					mediaRecorder = new MediaRecorder(stream, {
						mimeType: 'audio/webm; codecs=opus'
					});

					mediaRecorder.ondataavailable = event => {
						audioChunks.push(event.data);
					};

					mediaRecorder.onstop = async () => {
						const audioBlob = new Blob(audioChunks, {
							type: 'audio/webm; codecs=opus'
						});
						const audioUrl = URL.createObjectURL(audioBlob);
						const audio = document.getElementById('audioPlayback');
						audio.src = audioUrl;
						audio.style.display = 'block';

						// 自动上传录音文件到后端接口
						await uploadAudioFile(audioBlob);

						// 清空 audioChunks 以便下次录音
						audioChunks = [];
					};

					mediaRecorder.start();
					recording = true;
					document.getElementById('recordButton').textContent = '停止录音';
				} catch (err) {
					console.error('Error accessing media devices.', err);
				}
			}

			function stopRecording() {
				if (mediaRecorder && mediaRecorder.state !== 'inactive') {
					mediaRecorder.stop();
					mediaRecorder.stream.getTracks().forEach(track => track.stop()); // 停止媒体流轨道
				}
				recording = false;
				document.getElementById('recordButton').textContent = '开始录音';
			}

			async function uploadAudioFile(blob) {
				const formData = new FormData();
				formData.append('file', blob, 'recording.webm');

				try {
					const response = await fetch('http://127.0.0.1:30025/sound', {
						method: 'POST',
						body: formData,
					});

					if (!response.ok) {
						throw new Error(`HTTP error! status: ${response.status}`);
					}

					const result = await response.json();
					console.log('Server response:', result);
				} catch (error) {
					console.error('There was a problem with the fetch operation:', error);
				}
			}
		</script>

	</body>
</html>

python接口

@app.route('/sound', methods=['POST'])
def sound():
    file = request.files['file']
    # ... 处理文件
    return "SUCCESS"

;