最近我需要弄清楚另一件事,将我的 Assembly.ai 转录引擎连接到一个声音很大的前端。
第一步是请求访问启用了回声消除的麦克风。此功能内置于大多数现代浏览器中,有助于减少扬声器的反馈。
async function getMicrophoneStream() { const constraints = { audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } }; try { const stream = await navigator.mediaDevices.getUserMedia(constraints); return stream; } catch (err) { console.error('Error accessing the microphone', err); return null; } }
接下来,我们设置 Web Audio API 来处理音频流。这涉及创建 AudioContext 并连接各种节点,包括 DynamicsCompressorNode。
async function setupAudioProcessing(stream) { const audioContext = new AudioContext(); const source = audioContext.createMediaStreamSource(stream); // Create a DynamicsCompressorNode for additional processing const compressor = audioContext.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioContext.currentTime); // Example settings compressor.knee.setValueAtTime(40, audioContext.currentTime); compressor.ratio.setValueAtTime(12, audioContext.currentTime); compressor.attack.setValueAtTime(0, audioContext.currentTime); compressor.release.setValueAtTime(0.25, audioContext.currentTime); // Connect nodes source.connect(compressor); compressor.connect(audioContext.destination); return { audioContext, source, compressor }; }
最后,我们将音频处理设置与 Web Speech API 集成以执行语音识别。
async function startSpeechRecognition() { const stream = await getMicrophoneStream(); if (!stream) return; const { audioContext, source, compressor } = await setupAudioProcessing(stream); const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)(); recognition.continuous = true; recognition.interimResults = true; recognition.onresult = (event) => { for (let i = event.resultIndex; i < event.results.length; i++) { const transcript = event.results[i][0].transcript; console.log('Transcript:', transcript); } }; recognition.onerror = (event) => { console.error('Speech recognition error', event.error); }; recognition.start(); // Handle audio context resume if needed if (audioContext.state === 'suspended') { audioContext.resume(); } return recognition; } // Start the speech recognition process startSpeechRecognition();
希望您发现这很有用。
编码愉快!
蒂姆。
以上是如何使用 Web 音频 API 防止语音转录中的说话者反馈的详细内容。更多信息请关注PHP中文网其他相关文章!