This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-16 21:22:01 +02:00
1 parent 20b3af5483
commit 6860661d30
14 files changed
+136 -19

No files matched your search

@@ -24,6 +24,7 @@
let ttsModel = $state('tts-1');
let ttsVoice = $state('alloy');
let ttsFormat = $state('mp3');
let ttsPlaybackSpeed = $state(1);
let hasExistingTtsKey = $state(false);
let voiceModeSystemPrompt = $state('');
let voiceModeSttMode = $state<'browser' | 'provider'>('browser');
@@ -46,6 +47,8 @@
ttsModel = (config['audio.tts_model'] as string) || 'tts-1';
ttsVoice = (config['audio.tts_voice'] as string) || 'alloy';
ttsFormat = (config['audio.tts_format'] as string) || 'mp3';
const speed = Number(config['audio.tts_playback_speed']);
ttsPlaybackSpeed = Number.isFinite(speed) ? Math.min(Math.max(speed, 0.5), 2) : 1;
hasExistingTtsKey = !!config['audio.tts_api_key'];
voiceModeSystemPrompt = (config['audio.voice_mode_system_prompt'] as string) || '';
voiceModeSttMode =
@@ -68,6 +71,7 @@
'audio.tts_model': ttsModel,
'audio.tts_voice': ttsVoice,
'audio.tts_format': ttsFormat,
'audio.tts_playback_speed': ttsPlaybackSpeed,
'audio.voice_mode_system_prompt': voiceModeSystemPrompt,
'audio.voice_mode_stt_mode': voiceModeSttMode
};
@@ -236,6 +240,23 @@
<option value="pcm">PCM</option>
</select>
</div>
<div class="flex items-center justify-between gap-3">
<label class="text-xs text-gray-600 dark:text-gray-400" for="tts-playback-speed">
{$t('admin.audio.ttsPlaybackSpeed')}
</label>
<div class="flex items-center gap-2">
<input
id="tts-playback-speed"
type="range"
min="0.5"
max="2"
step="0.05"
bind:value={ttsPlaybackSpeed}
class="w-28 accent-gray-700 dark:accent-gray-300"
/>
<span class="w-9 text-right text-xs text-gray-500 dark:text-gray-400">{ttsPlaybackSpeed.toFixed(2)}x</span>
</div>
</div>
<p class="text-[11px] text-gray-400 dark:text-gray-600">
{$t('admin.audio.ttsHint')}
</p>
@@ -37,7 +37,7 @@
ttsEnabled,
ttsConfigured,
ttsFormat,
getTtsAudioElement,
setTtsAudioPlaybackSource,
ttsPlaybackEnabled,
ttsVoice,
unlockTtsAudioPlayback,
@@ -82,6 +82,8 @@
let ttsInsideCodeFence = false;
let ttsPlaying = false;
let ttsGeneration = 0;
let ttsPrepareCursor = 0;
let ttsPreparing = 0;
let ttsAudio: HTMLAudioElement | null = null;
let ttsObjectUrl: string | null = null;
let ttsErrorShown = false;
@@ -94,6 +96,7 @@
const ttsAudioCache = new Map<string, Blob>();
const ttsPreparedAudio = new Map<string, PreparedTtsAudio>();
const TTS_AUDIO_CACHE_LIMIT_BYTES = 20 * 1024 * 1024;
const TTS_MAX_PREFETCH = 2;
// ── Windowed rendering ──────────────────────────────────────
// Only render the last N turns to keep the DOM light for long chats.
@@ -958,6 +961,8 @@
ttsStopRequested = true;
ttsGeneration += 1;
ttsQueue = [];
ttsPrepareCursor = 0;
ttsPreparing = 0;
resetTtsBuffer();
for (const pending of ttsPreparedAudio.values()) pending.controller.abort();
ttsPreparedAudio.clear();
@@ -998,18 +1003,21 @@
.trim();
}
function findSpeechBoundary(text: string): number {
if (text.length < 60) return -1;
for (let i = 40; i < text.length; i++) {
function findSpeechBoundary(text: string, firstChunk = false): number {
const min = firstChunk ? 35 : 60;
const scanFrom = firstChunk ? 30 : 40;
const hardMax = firstChunk ? 95 : 220;
if (text.length < min) return -1;
for (let i = scanFrom; i < text.length; i++) {
const ch = text[i];
const next = text[i + 1] || '';
if ((ch === '.' || ch === '!' || ch === '?' || ch === '\n') && (!next || /\s/.test(next))) {
return i + 1;
}
}
if (text.length > 220) {
const idx = text.lastIndexOf(' ', 220);
return idx > 80 ? idx : 220;
if (text.length > hardMax) {
const idx = text.lastIndexOf(' ', hardMax);
return idx > min ? idx : hardMax;
}
return -1;
}
@@ -1025,7 +1033,7 @@
if (!speakable.trim()) return;
ttsBuffer += speakable;
let boundary = findSpeechBoundary(ttsBuffer);
let boundary = findSpeechBoundary(ttsBuffer, ttsQueue.length === 0 && !ttsPlaying);
while (boundary > 0) {
const chunk = cleanSpeechText(ttsBuffer.slice(0, boundary));
ttsBuffer = ttsBuffer.slice(boundary);
@@ -1043,7 +1051,7 @@
function enqueueSpeech(text: string) {
ttsQueue = [...ttsQueue, text];
void prepareTtsAudio(text, ttsGeneration);
scheduleTtsPrepare(ttsGeneration);
if (!ttsPlaying) void playTtsQueue(ttsGeneration);
}
@@ -1134,6 +1142,24 @@
voiceModeEnabled.set(false);
}
function scheduleTtsPrepare(generation: number) {
while (
generation === ttsGeneration &&
ttsPreparing < TTS_MAX_PREFETCH &&
ttsPrepareCursor < ttsQueue.length
) {
const text = ttsQueue[ttsPrepareCursor++];
ttsPreparing += 1;
void prepareTtsAudio(text, generation)
.catch(() => {})
.finally(() => {
if (generation !== ttsGeneration) return;
ttsPreparing = Math.max(0, ttsPreparing - 1);
scheduleTtsPrepare(generation);
});
}
}
function prepareTtsAudio(text: string, generation: number): Promise<Blob> {
const cacheKey = ttsCacheKey(text);
const cached = getCachedTtsAudio(cacheKey);
@@ -1154,6 +1180,7 @@
.then(async (response) => {
if (!response.ok) throw new Error(await readTtsError(response));
const blob = await response.blob();
if (blob.size <= 0) throw new Error('empty audio response');
cacheTtsAudio(cacheKey, blob);
return blob;
})
@@ -1172,16 +1199,20 @@
try {
while (generation === ttsGeneration && ttsQueue.length > 0) {
if (!shouldUseTts()) break;
const text = ttsQueue.shift();
if (!text) continue;
const text = ttsQueue[0];
if (!text) {
ttsQueue = ttsQueue.slice(1);
if (ttsPrepareCursor > 0) ttsPrepareCursor -= 1;
continue;
}
scheduleTtsPrepare(generation);
const blob = await prepareTtsAudio(text, generation);
if (generation !== ttsGeneration) break;
if (ttsObjectUrl) URL.revokeObjectURL(ttsObjectUrl);
ttsObjectUrl = URL.createObjectURL(blob);
ttsAudio = getTtsAudioElement() ?? new Audio();
ttsAudio.src = ttsObjectUrl;
ttsAudio = setTtsAudioPlaybackSource(ttsObjectUrl) ?? new Audio(ttsObjectUrl);
await new Promise<void>((resolve, reject) => {
const audio = ttsAudio!;
audio.onended = () => resolve();
@@ -1197,6 +1228,11 @@
ttsObjectUrl = null;
}
ttsAudio = null;
if (generation !== ttsGeneration) break;
if (ttsQueue[0] === text) {
ttsQueue = ttsQueue.slice(1);
if (ttsPrepareCursor > 0) ttsPrepareCursor -= 1;
}
}
} catch (err: any) {
if (!ttsStopRequested && err?.name !== 'AbortError' && !ttsErrorShown) {
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -596,6 +596,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -480,6 +480,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
@@ -481,6 +481,7 @@
"admin.audio.ttsKeyPlaceholder": "Leave blank to reuse STT key",
"admin.audio.ttsVoice": "Voice",
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsPlaybackSpeed": "Playback speed",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
+29
View File
@@ -21,6 +21,7 @@ export const ttsEnabled = writable<boolean>(false);
export const ttsConfigured = writable<boolean>(false);
export const ttsVoice = writable<string>('alloy');
export const ttsFormat = writable<string>('mp3');
export const ttsPlaybackSpeed = writable<number>(1);
export const voiceModeEnabled = writable<boolean>(false);
export const voiceModeSttMode = writable<'browser' | 'provider'>('browser');
export const ttsPlaybackEnabled = writable<boolean>(
@@ -33,21 +34,41 @@ const SILENT_WAV =
let ttsAudioElement: HTMLAudioElement | null = null;
let ttsAudioContext: AudioContext | null = null;
let ttsAudioUnlocked = false;
let ttsAudioUseToken = 0;
let currentTtsPlaybackSpeed = 1;
ttsPlaybackEnabled.subscribe((v) => {
if (typeof localStorage !== 'undefined') localStorage.setItem('ttsPlaybackEnabled', String(v));
});
ttsPlaybackSpeed.subscribe((v) => {
currentTtsPlaybackSpeed = Number.isFinite(v) ? Math.min(Math.max(v, 0.5), 2) : 1;
if (ttsAudioElement) ttsAudioElement.playbackRate = currentTtsPlaybackSpeed;
});
export function getTtsAudioElement(): HTMLAudioElement | null {
if (typeof Audio === 'undefined') return null;
if (!ttsAudioElement) {
ttsAudioElement = new Audio();
ttsAudioElement.preload = 'auto';
(ttsAudioElement as HTMLAudioElement & { playsInline?: boolean }).playsInline = true;
ttsAudioElement.playbackRate = currentTtsPlaybackSpeed;
}
return ttsAudioElement;
}
export function setTtsAudioPlaybackSource(src: string): HTMLAudioElement | null {
const audio = getTtsAudioElement();
if (!audio) return null;
ttsAudioUseToken += 1;
audio.pause();
audio.volume = 1;
audio.muted = false;
audio.playbackRate = currentTtsPlaybackSpeed;
audio.src = src;
return audio;
}
export async function unlockTtsAudioPlayback() {
if (typeof window === 'undefined') return;
@@ -69,8 +90,10 @@ export async function unlockTtsAudioPlayback() {
const audio = getTtsAudioElement();
if (audio && !ttsAudioUnlocked) {
try {
const unlockToken = ++ttsAudioUseToken;
audio.src = SILENT_WAV;
audio.volume = 0;
audio.playbackRate = 1;
const started = audio.play();
unlocks.push(
Promise.resolve(started)
@@ -78,11 +101,13 @@ export async function unlockTtsAudioPlayback() {
ttsAudioUnlocked = true;
})
.finally(() => {
if (unlockToken !== ttsAudioUseToken) return;
audio.pause();
audio.currentTime = 0;
audio.removeAttribute('src');
audio.load();
audio.volume = 1;
audio.playbackRate = currentTtsPlaybackSpeed;
})
);
} catch {}
@@ -102,6 +127,7 @@ export async function refreshAudioState() {
tts_configured: boolean;
tts_voice: string;
tts_format: string;
tts_playback_speed?: number;
voice_mode_stt_mode?: string;
}>('/api/audio/state');
voiceMemosEnabled.set(data.voice_memos_enabled === true);
@@ -114,12 +140,15 @@ export async function refreshAudioState() {
ttsConfigured.set(data.tts_configured === true);
ttsVoice.set(data.tts_voice || 'alloy');
ttsFormat.set(data.tts_format || 'mp3');
const speed = Number(data.tts_playback_speed);
ttsPlaybackSpeed.set(Number.isFinite(speed) ? Math.min(Math.max(speed, 0.5), 2) : 1);
voiceModeSttMode.set(data.voice_mode_stt_mode === 'provider' ? 'provider' : 'browser');
} catch {
voiceMemosEnabled.set(false);
sttConfigured.set(false);
ttsEnabled.set(false);
ttsConfigured.set(false);
ttsPlaybackSpeed.set(1);
voiceModeSttMode.set('browser');
}
}
+27 -6
View File
@@ -54,6 +54,7 @@ class AudioStateResponse(BaseModel):
tts_configured: bool
tts_voice: str
tts_format: str
tts_playback_speed: float
voice_mode_stt_mode: str
@@ -200,6 +201,12 @@ async def audio_state(request: Request):
quality = await Config.get("audio.recording_quality")
if quality not in ("high", "medium", "low"):
quality = "high"
playback_speed = await Config.get("audio.tts_playback_speed")
try:
playback_speed = float(playback_speed)
except (TypeError, ValueError):
playback_speed = 1.0
playback_speed = min(max(playback_speed, 0.5), 2.0)
return AudioStateResponse(
voice_memos_enabled=await Config.get("audio.voice_memos_enabled") is True,
@@ -210,6 +217,7 @@ async def audio_state(request: Request):
tts_configured=bool(tts_key or stt_key),
tts_voice=str((await Config.get("audio.tts_voice")) or "alloy"),
tts_format=str((await Config.get("audio.tts_format")) or "mp3"),
tts_playback_speed=playback_speed,
voice_mode_stt_mode=str((await Config.get("audio.voice_mode_stt_mode")) or "browser"),
)
@@ -495,11 +503,15 @@ async def speech(body: SpeechRequest, request: Request):
cache_json_path = cache_dir / f"{key}.json"
if cache_audio_path.exists():
try:
return Response(
content=cache_audio_path.read_bytes(),
media_type=_audio_media_type(str(fmt)),
headers={"X-CPTR-Audio-Cache": "hit"},
)
if cache_audio_path.stat().st_size <= 0:
cache_audio_path.unlink(missing_ok=True)
cache_json_path.unlink(missing_ok=True)
else:
return Response(
content=cache_audio_path.read_bytes(),
media_type=_audio_media_type(str(fmt)),
headers={"X-CPTR-Audio-Cache": "hit"},
)
except OSError:
pass
@@ -521,6 +533,10 @@ async def speech(body: SpeechRequest, request: Request):
except httpx.ConnectError:
raise HTTPException(502, "Could not connect to TTS API")
if not resp.content:
raise HTTPException(502, "TTS API returned empty audio.")
cache_state = "disabled"
if cache_audio_path and cache_json_path:
_write_bytes_atomic(cache_audio_path, resp.content)
_write_json_atomic(
@@ -536,5 +552,10 @@ async def speech(body: SpeechRequest, request: Request):
"content_type": _audio_media_type(str(fmt)),
},
)
cache_state = "write"
return Response(content=resp.content, media_type=_audio_media_type(str(fmt)))
return Response(
content=resp.content,
media_type=_audio_media_type(str(fmt)),
headers={"X-CPTR-Audio-Cache": cache_state},
)