/* Explicit FunASR streaming microphone input. Offline sentence boundary stops capture and submits once; no RTC publishing. */ window.TeacherMic=function({input,button,cancelButton,message,onChange,canStart,onFinal}){ const AudioCtx=window.AudioContext||window.webkitAudioContext; const supported=!!(window.isSecureContext&&navigator.mediaDevices?.getUserMedia&&AudioCtx&&window.AudioWorkletNode); const label=button.querySelector('span');let job=null,enabled=false; const endpoint='wss://asr.vrfab.com'; const api={get active(){return !!job},get recording(){return !!job&&!job.audioStopped},configure(v){enabled=v===true;render()},update:render,cancel}; function say(s){message.textContent=s} function render(){ const phase=job?.phase; label.textContent=phase==='recording'?'结束':phase==='finishing'?'收尾中':job?'连接中':'语音'; button.dataset.state=phase||'idle';button.disabled=!supported||!enabled||!!job&&phase!=='recording'||!job&&!canStart(); button.setAttribute('aria-pressed',String(phase==='recording')); button.setAttribute('aria-label',phase==='recording'?'结束麦克风语音输入':'开始麦克风语音输入'); button.title=!supported?'当前浏览器不支持实时录音,请使用文字输入':'点击语音,说完一句后自动发送;可随时取消'; cancelButton.hidden=!job;input.readOnly=!!job; } function valid(j){return job===j&&!document.hidden} function stopAudio(j){ if(j.audioStopped)return;j.audioStopped=true; j.stream?.getTracks().forEach(t=>{t.onended=null;t.stop()}); try{j.source?.disconnect();j.node?.disconnect();j.gain?.disconnect()}catch{} j.ctx?.close().catch(()=>{});clearTimeout(j.timer);clearTimeout(j.flushTimer); } function release(j){ stopAudio(j);j.abort?.abort();clearTimeout(j.watchdog); if(j.ws){j.ws.onopen=j.ws.onmessage=j.ws.onclose=j.ws.onerror=null;try{j.ws.close(1000)}catch{}} } function finish(j,text){ if(job!==j)return;release(j);job=null;render();onChange();if(text)say(text); } function cancel(text='语音输入已取消,录音前草稿已保留。'){ const j=job;if(!j)return;input.value=j.draft;input.dispatchEvent(new Event('input',{bubbles:true}));finish(j,text); } function display(j){ const text=j.committed+j.partial; const next=j.draft+(j.draft&&text&&!j.draft.endsWith('\n')?'\n':'')+text; if(next.length>input.maxLength){finish(j,'输入已达到字数上限,已保留当前文字,请编辑后再录音。');return false} input.value=next;input.dispatchEvent(new Event('input',{bubbles:true}));return true; } function complete(j,timeout=false){ if(!valid(j))return; const hasText=!!(j.committed+j.partial).trim(); finish(j,!hasText?'没有识别到清晰的讲话,请检查麦克风后重试。':timeout?'已保留实时识别文字,句尾校正未及时返回;请检查后发送。':'语音已转成文字,可修改后点击发送。'); if(hasText){input.focus();input.setSelectionRange(input.value.length,input.value.length)} } function sentenceDone(j){ if(!valid(j)||j.submitted)return;j.submitted=true; const text=j.committed.trim(); // Offline is the sentence boundary even when FunASR is_final is false. // Stop capture before sending the question; discard any queued later audio. stopAudio(j); if(!j.endSent&&j.ws?.readyState===1){j.endSent=true;try{j.ws.send(JSON.stringify({is_speaking:false,is_end:true}))}catch{}} input.value=j.draft;input.dispatchEvent(new Event('input',{bubbles:true})); finish(j,text?'':'没有识别到清晰的讲话,请检查麦克风后重试。'); if(!text)return; let sent=false;try{sent=onFinal?.(text)===true}catch{} if(!sent){ input.value=j.draft+(j.draft&&!j.draft.endsWith('\n')?'\n':'')+text; input.dispatchEvent(new Event('input',{bubbles:true})); say('语音已识别,但当前无法发送;文字已保留,请连接就绪后手动发送。'); } } function receive(j,e){ if(!valid(j))return; try{ if(typeof e.data!=='string'||e.data.length>65536)throw Error(); const d=JSON.parse(e.data);if(!d||typeof d!=='object'||d.error)throw Error(); if(d.wav_name&&d.wav_name!==j.name)return; const text=typeof d.text==='string'?d.text:''; // This deployment sends an empty final acknowledgement without mode. if(!d.mode&&d.is_final===true&&!text)return; if(d.mode==='2pass-online')j.partial+=text; else if(d.mode==='2pass-offline'||d.mode==='offline'){j.committed+=text;j.partial='';if(display(j))sentenceDone(j);return} else if(d.is_end)return; else throw Error(); display(j); }catch{finish(j,'识别服务返回异常,已保留当前文字,请稍后手动重试。')} } function sendPCM(j,b){ if(!valid(j)||j.endSent||j.ws?.readyState!==1)return; if(!(b instanceof ArrayBuffer)||b.byteLength%2||b.byteLength>1920){finish(j,'录音数据异常,请重新录制。');return} j.bytes+=b.byteLength; if(j.bytes>960000||j.ws.bufferedAmount>128000){finish(j,'语音上传中断,已保留当前文字,请检查网络。');return} try{j.ws.send(b)}catch{finish(j,'语音连接中断,已保留当前文字。')} } function endInput(j){ if(!valid(j)||j.endSent)return;j.phase='finishing';stopAudio(j);j.endSent=true;render();onChange(); try{j.ws.send(JSON.stringify({is_speaking:false,is_end:true}))} catch{finish(j,'语音连接中断,已保留当前文字。');return} say('正在确认句尾文字…'); j.watchdog=setTimeout(()=>complete(j,true),5000); } function stopRecording(){ const j=job;if(!j||j.phase!=='recording')return; j.phase='finishing';clearTimeout(j.timer);render(); j.node.port.postMessage('stop'); j.flushTimer=setTimeout(()=>{if(valid(j))finish(j,'录音收尾中断,已保留当前文字,请检查后发送。')},1000); } async function start(){ if(job||!supported||!enabled||!canStart())return; const j={phase:'requesting',draft:input.value,committed:'',partial:'',bytes:0,name:'teacher_'+crypto.randomUUID().replaceAll('-','')}; job=j;render();onChange();say('请允许使用麦克风;讲话将实时转成文字。'); j.watchdog=setTimeout(()=>{if(valid(j))cancel('等待麦克风授权超时,可点击语音重新尝试。')},20000); try{ // Resume within the click gesture, including Safari's audio policy. j.ctx=new AudioCtx({sampleRate:16000}); const resuming=j.ctx.resume();resuming.catch(()=>{}); const stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:true,noiseSuppression:true,autoGainControl:true},video:false}); if(!valid(j)){stream.getTracks().forEach(t=>t.stop());return} j.stream=stream;clearTimeout(j.watchdog);j.phase='connecting';render(); say('正在连接语音识别,请稍候…'); j.watchdog=setTimeout(()=>{if(valid(j))finish(j,'语音服务连接超时,请稍后手动重试。')},8000); await resuming; if(!valid(j))return; if(j.ctx.state!=='running')throw Error('audio'); // Fetch first so Windows' .js MIME mapping cannot reject AudioWorklet modules. j.abort=new AbortController(); const response=await fetch('/static/teacher-test/teacher-pcm-worklet.js?v=20261107-funasr2',{credentials:'same-origin',signal:j.abort.signal}); if(!response.ok)throw Error('worklet'); const code=await response.text();if(!valid(j))return; const moduleURL=URL.createObjectURL(new Blob([code],{type:'application/javascript'})); try{await j.ctx.audioWorklet.addModule(moduleURL)}finally{URL.revokeObjectURL(moduleURL)} if(!valid(j))return; const ws=new WebSocket(endpoint);j.ws=ws; ws.onmessage=e=>receive(j,e); ws.onerror=()=>{if(valid(j))finish(j,'无法连接语音服务,已保留当前文字,请稍后手动重试。')}; ws.onclose=()=>{if(valid(j))finish(j,'语音连接已断开,已保留当前文字,请稍后手动重试。')}; ws.onopen=()=>{ if(!valid(j)){ws.close();return} try{ clearTimeout(j.watchdog); ws.send(JSON.stringify({mode:'2pass',wav_name:j.name,wav_format:'pcm',audio_fs:16000,is_speaking:true,chunk_size:[5,10,5],chunk_interval:10,encoder_chunk_look_back:4,decoder_chunk_look_back:1,hotwords:JSON.stringify({'知微':20,'VRFAB':20}),itn:true})); j.node=new AudioWorkletNode(j.ctx,'teacher-pcm',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]}); j.node.port.onmessage=e=>{if(!valid(j))return;if(e.data.pcm)sendPCM(j,e.data.pcm);if(e.data.flushed)endInput(j)}; j.node.onprocessorerror=()=>{if(valid(j))finish(j,'麦克风处理异常,已保留当前文字。')}; j.source=j.ctx.createMediaStreamSource(stream);j.gain=j.ctx.createGain();j.gain.gain.value=0; j.source.connect(j.node);j.node.connect(j.gain);j.gain.connect(j.ctx.destination); for(const t of stream.getAudioTracks())t.onended=()=>{if(valid(j)&&j.phase==='recording')finish(j,'麦克风已断开,已保留当前文字。')}; j.phase='recording';render();onChange();say('正在听,说完一句后会自动发送;可随时取消,最多30秒。'); j.timer=setTimeout(stopRecording,30000); }catch{finish(j,'实时录音未能开始,请检查麦克风或使用文字输入。')} }; }catch(e){ if(job!==j)return; const errors={NotAllowedError:'未获得麦克风权限,请在浏览器地址栏允许后重试。',NotFoundError:'未找到麦克风,请连接设备后重试。',NotReadableError:'麦克风被占用或无法读取,请检查设备。'}; finish(j,errors[e.name]||'当前浏览器无法启动实时录音,请使用文字输入。'); } } button.addEventListener('click',()=>job?.phase==='recording'?stopRecording():start()); cancelButton.addEventListener('click',()=>cancel()); document.addEventListener('keydown',e=>{if(e.key==='Escape'&&job){e.preventDefault();cancel()}}); document.addEventListener('visibilitychange',()=>{if(document.hidden)cancel('已停止语音输入,录音前草稿已保留。')}); window.addEventListener('pagehide',()=>cancel('')); window.addEventListener('offline',()=>cancel('网络已断开,语音输入已取消。')); render();return api; };