Files
DeepTutor/web/lib/streaming-speech.ts

111 lines
3.8 KiB
TypeScript

type Segment = {
source: AudioBufferSourceNode
buffer: AudioBuffer
start: number
offset: number
}
/** Schedules the mono PCM16 frames from a single read-aloud response. */
export class StreamingSpeech {
private readonly segments = new Set<Segment>()
private nextStart = 0
private drained?: () => void
private reader?: ReadableStreamDefaultReader<Uint8Array>
private stopped = false
constructor(
private readonly context: AudioContext,
private readonly ready: Promise<boolean>,
private rate: number,
) {}
private schedule(buffer: AudioBuffer, offset = 0) {
const source = this.context.createBufferSource()
source.buffer = buffer
source.connect(this.context.destination)
source.playbackRate.value = this.rate
const start = Math.max(this.nextStart, this.context.currentTime + 0.08)
const segment = { source, buffer, start, offset }
this.segments.add(segment)
source.onended = () => {
this.segments.delete(segment)
if (!this.segments.size) this.drained?.()
}
source.start(start, offset)
this.nextStart = start + (buffer.duration - offset) / this.rate
}
setPlaybackRate(rate: number) {
if (!Number.isFinite(rate) || rate <= 0 || rate === this.rate) return
const now = this.context.currentTime
const previousRate = this.rate
this.rate = rate
this.nextStart = now
for (const segment of Array.from(this.segments)) {
this.segments.delete(segment)
segment.source.onended = null
segment.source.stop()
const offset = segment.offset + Math.max(0, now - segment.start) * previousRate
if (offset < segment.buffer.duration) this.schedule(segment.buffer, offset)
}
if (!this.segments.size) this.drained?.()
}
async play(body: ReadableStream<Uint8Array>, onStart: () => void) {
if (!(await this.ready) || this.stopped) throw new Error('Audio context unavailable')
const reader = body.getReader()
this.reader = reader
const decoder = new TextDecoder()
let pending = ''
let started = false
let complete = false
try {
while (!this.stopped) {
const packet = await reader.read()
if (this.stopped) return
pending += decoder.decode(packet.value, { stream: !packet.done })
const lines = pending.split('\n')
pending = lines.pop()!
for (const line of lines) {
if (!line.trim()) continue
const event = JSON.parse(line)
if (event.error) throw new Error('Speech synthesis failed')
if (event.done === true) {
complete = true
continue
}
if (complete || !event.pcm || event.sample_rate !== 24000) throw new Error('Invalid speech frame')
const pcm = Uint8Array.from(atob(event.pcm), char => char.charCodeAt(0))
if (!pcm.length || pcm.length % 2) throw new Error('Incomplete PCM sample')
const buffer = this.context.createBuffer(1, pcm.length / 2, event.sample_rate)
const samples = buffer.getChannelData(0)
const view = new DataView(pcm.buffer)
for (let i = 0; i < samples.length; i++) {
samples[i] = view.getInt16(i * 2, true) / 32768
}
this.schedule(buffer)
if (!started) {
started = true
onStart()
}
}
if (packet.done) break
}
if (!started || !complete || pending.trim()) throw new Error('Incomplete speech stream')
if (this.segments.size) await new Promise<void>(resolve => { this.drained = resolve })
} finally {
reader.releaseLock()
this.reader = undefined
}
}
stop() {
if (this.stopped) return
this.stopped = true
void this.reader?.cancel().catch(() => {})
this.drained?.()
this.segments.clear()
void this.context.close().catch(() => {})
}
}