最近我需要弄清楚另一件事,將我的 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 { 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();
希望您發現這很有用。
編碼愉快!
提姆。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3