最近我還需要弄清楚另一件事,將我的 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中文網其他相關文章!