@@ -11,7 +11,12 @@ import {
1111 type VoiceRecorder ,
1212 type VoiceTranscriber ,
1313} from "@t3tools/client-runtime/voice-input" ;
14- import type { DictationSessionId , EnvironmentId } from "@t3tools/contracts" ;
14+ import {
15+ DICTATION_MAX_SECONDS ,
16+ DICTATION_SAMPLE_RATE ,
17+ type DictationSessionId ,
18+ type EnvironmentId ,
19+ } from "@t3tools/contracts" ;
1520import * as Base64 from "effect/encoding/Base64" ;
1621import type { AtomRegistry } from "effect/reactivity" ;
1722
@@ -77,6 +82,7 @@ export function createStreamingDictation(input: {
7782 const capture = new PcmCapture ( ) ;
7883 const level = createDictationLevel ( ) ;
7984 let session : DictationSession | null = null ;
85+ let captureStartedAt = 0 ;
8086 let limitTimer : ReturnType < typeof setTimeout > | null = null ;
8187
8288 const run = < W , A , E > ( command : AtomCommand < W , A , E > , value : W ) =>
@@ -202,10 +208,13 @@ export function createStreamingDictation(input: {
202208 const current = session ;
203209 if ( current === null ) throw new Error ( "No dictation session is open." ) ;
204210 clearLimit ( ) ;
205- limitTimer = setTimeout ( ( ) => {
206- limitTimer = null ;
207- void capture . stop ( ) . then ( ( ) => input . finishedAtLimit ( sessionUri ( current ) ) ) ;
208- } , forDuration * 1_000 ) ;
211+ limitTimer = setTimeout (
212+ ( ) => {
213+ limitTimer = null ;
214+ void capture . stop ( ) . then ( ( ) => input . finishedAtLimit ( sessionUri ( current ) ) ) ;
215+ } ,
216+ Math . max ( 0 , forDuration * 1_000 - ( Date . now ( ) - captureStartedAt ) ) ,
217+ ) ;
209218 } ,
210219 stop : async ( ) => {
211220 clearLimit ( ) ;
@@ -231,8 +240,19 @@ export function createStreamingDictation(input: {
231240 }
232241 await capture . prepare ( ) ;
233242 const current = session ;
243+ captureStartedAt = Date . now ( ) ;
244+ let capturedBytes = 0 ;
245+ const maxBytes = DICTATION_MAX_SECONDS * DICTATION_SAMPLE_RATE * 2 ;
234246 capture . start ( ( frame ) => {
235- if ( current !== null ) sendChunk ( current , frame ) ;
247+ const remaining = maxBytes - capturedBytes ;
248+ if ( current === null || remaining <= 0 ) return ;
249+ const chunk = frame . byteLength > remaining ? frame . slice ( 0 , remaining ) : frame ;
250+ capturedBytes += chunk . byteLength ;
251+ sendChunk ( current , chunk ) ;
252+ if ( capturedBytes === maxBytes ) {
253+ clearLimit ( ) ;
254+ void capture . stop ( ) . then ( ( ) => input . finishedAtLimit ( sessionUri ( current ) ) ) ;
255+ }
236256 } , level . set ) ;
237257 return { granted : true , canAskAgain : true } ;
238258 } ,
0 commit comments