HEL-900: preserve visual director custom voice frontend unchanged

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-28 00:16:59 +08:00
co-authored by multica-agent
parent ce7279e68f
commit 701442d4d4
8 changed files with 1109 additions and 5 deletions
+10 -5
View File
@@ -4,12 +4,13 @@ import type { DemoState, Settings, Theme } from '../domain/model';
import { delay } from '../adapters/demo';
import { exportDemo, parseState } from '../adapters/storage';
import { BaseColor, Button, Field, Icon, Modal, Status } from '../shared/ui';
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
import { VoiceSection, type VoiceCap } from './VoiceSection';
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['voice', 'mic', '她的声音'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
// What each section can actually do here (HEL-815 capability tags): read-only, adjustable, demo only, not connected, this device.
type Cap = 'ro' | 'edit' | 'demo' | 'off' | 'live' | 'local';
const CAP: Record<Cap, [string, string]> = { ro: ['只读', ''], edit: ['可以调整', 'accent'], demo: ['演示数据', 'demo'], off: ['未接入', 'off'], live: ['文字已接通', 'ok'], local: ['本机生效', 'ok'] };
const capOf = (id: string, real: boolean): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo';
const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调整', display: '本机生效' };
const capOf = (id: string, real: boolean, voice: VoiceCap = 'unknown'): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'voice' ? real ? voice === 'off' ? 'off' : 'edit' : 'demo' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo';
const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调整', voice: '上传 · 录音 · 试听', display: '本机生效' };
function CapTag({ cap }: { cap: Cap }) { const [text, tone] = CAP[cap]; return <span className={`tag cap ${tone}`}>{text}</span>; }
// Honest placeholder for a capability that is not connected: what it will do once connected, and that nothing happens now.
function Off({ title, will, now }: { title: string; will: string; now: string }) { return <div className="off-card"><p className="off-t">{title}</p><p>{will}</p><p className="d-dim">{now}</p></div>; }
@@ -32,10 +33,12 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
const approvedNavigation = useRef(false);
const pendingNavigation = useRef<(() => void) | null>(null);
const [serviceHealth, setServiceHealth] = useState<Health>();
// 她的声音 (HEL-900): an unregistered reference counts as unsaved; the tag follows what the server reports.
const [voiceDirty, setVoiceDirty] = useState(false), [voiceCap, setVoiceCap] = useState<VoiceCap>('unknown');
const request = useRef<AbortController | null>(null), generation = useRef(0), feedback = useRef<HTMLDivElement>(null);
useEffect(()=>{if(message) feedback.current?.scrollIntoView({block:'center'});},[message]);
const latestState = useRef(state); latestState.current = state;
const dirtySections: Record<string, boolean> = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced};
const dirtySections: Record<string, boolean> = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced, voice: real && voiceDirty};
const dirty = !!dirtySections[section], anyDirty = Object.values(dirtySections).some(Boolean);
useEffect(() => { if (!open) {
request.current?.abort();
@@ -168,7 +171,7 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
<div><h4>后来慢慢有的<small>成长 · 单独记录</small></h4>{p?.growth.length ? <ul>{p.growth.map(g => <li key={g.id}>{g.text}<small>{SOURCE[g.source] || '有来处的成长'} · {day(g.ts)}</small></li>)}</ul> : <p className="d-dim">{!p ? '读取中…' : '还没有记下的成长。长期记忆尚未接通,聊天记录已独立保存。'}</p>}</div></div>;
}
const sectionLabel = (id: string) => real && id === 'backup' ? '备份' : sections.find(s => s[0] === id)?.[2] || '';
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><div className="ttl"><small className="kicker"><span className="k-wide">慢慢安排你们的世界 · {real ? '服务器档案' : '仅本机演示'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>设置</h2></div><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon]) => { const cap = capOf(id, real); return <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/><span className="sl">{sectionLabel(id)}<small aria-hidden="true">{NOTE[id] || CAP[cap][0]}</small></span><i className="dirty"/><span className="chev" aria-hidden="true"><Icon name="next"/></span></button>; })}<p className="snav-foot">首版只有一位她 · 没有重建或清空</p></nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><div className="sec-h"><h3>{section === 'her' ? state.identity.name : sectionLabel(section)}</h3><CapTag cap={capOf(section, real)}/></div><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : real ? '资料保存在服务器。尚未接通的功能写明接上以后能做什么,现在不会发生任何事。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><div className="ttl"><small className="kicker"><span className="k-wide">慢慢安排你们的世界 · {real ? '服务器档案' : '仅本机演示'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>设置</h2></div><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon]) => { const cap = capOf(id, real); return <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/><span className="sl">{sectionLabel(id)}<small aria-hidden="true">{NOTE[id] || CAP[cap][0]}</small></span><i className="dirty"/><span className="chev" aria-hidden="true"><Icon name="next"/></span></button>; })}<p className="snav-foot">首版只有一位她 · 没有重建或清空</p></nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><div className="sec-h"><h3>{section === 'her' ? state.identity.name : sectionLabel(section)}</h3>{!(real && section === 'voice' && voiceCap === 'unknown') && <CapTag cap={capOf(section, real, voiceCap)}/>}</div><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : section === 'voice' ? `换${state.identity.name}说话的声音:给一段参考声音,先试听,再给她用。只换声音,名字、底色、关系、聊天和记忆都不变。` : real ? '资料保存在服务器。尚未接通的功能写明接上以后能做什么,现在不会发生任何事。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
{section === 'her' && <><dl className="kv"><dt>名字</dt><dd>{state.identity.name}<small>由你在初次创建时起的名字;首版不另设改名流程。</small></dd><dt>生辰</dt><dd>{state.identity.birth} · {state.identity.hour}<small><Icon name="lock"/>只读</small></dd></dl>
<h4 className="sub-h">她的底色<small>系统资料 · 每轮对话都会重新带上 · 关系设定不能改写</small></h4><BaseColor color={real ? (state.identity as RealIdentity).color : undefined}/>
<h4 className="sub-h">她怎么理解自己<small>模型诠释 · 会延续,也会变化</small></h4>{real ? personaView() : <Off title="演示不生成她对自己的诠释。" will="接上以后,这里是她在相处和生活里慢慢形成的自我理解,带版本和时间;不是固定模板,也不能直接改写。" now="现在这里不显示任何固定段落,避免把模板当成她的个性。"/>}
@@ -178,6 +181,8 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
{!real && section === 'appearance' && <><div className="card">当前素材:{state.settings.appearance}<small className="d-foot">参考静帧,不代表最终人物素材。</small></div><Field label="选择本地素材清单(演示 JSON)" hint="真实素材包格式尚待定稿。只读 JSON,不加载清单中的 URL 或脚本。"><input type="file" accept=".json,application/json" onChange={e => void importMaterial(e.target.files?.[0])}/></Field>{check && <Status text={check} error={!material}/>} {material && <><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前参考"/><figcaption>当前参考</figcaption></figure><figure className="new"><img src="/assets/her-room.jpg" alt="新外观模拟效果"/><figcaption>模拟效果 · 未加载素材</figcaption></figure></div><Button primary onClick={() => setConfirm('appearance')}>应用演示外观标识</Button></>}<p className="d-foot">只演示检查、预览与确认。媒体真实性未校验,不声称完成素材导入。</p></>}
{!real && section === 'backup' && <><div className="card"><h4>真实后台备份 · 未接通</h4><p>服务器每日备份、数据库和素材完整备份均未提供。本地文件不包含真实后台资料。</p></div><div className="card"><h4>你自己的演示资料</h4><p>包括本机档案、设置、文字、演示日子和回忆;不包含素材文件。</p><Button onClick={() => { exportDemo(state); setMessage('已生成本地演示 JSON 下载。'); setError(false); }}>导出本地演示 JSON</Button></div><Field label="恢复同一位她的本地演示 JSON"><input type="file" accept=".json,application/json" onChange={e => void importBackup(e.target.files?.[0])}/></Field>{restore && <Button onClick={() => { setConfirmText(''); setConfirm('restore'); }}>检查通过,继续恢复</Button>}</>}
{!real && section === 'services' && <>{Object.entries(draft.settings.services).map(([key, value]) => <div className="svc" key={key}><div className="nm">{key}<small>未接通 · 测试仅演示,不发网络请求</small></div><Button onClick={() => { setMessage(`${key}:界面演示,未真实检测。相关功能暂不可用,文字演示仍可使用。`); setError(false); }}>测试连接</Button><input className="input" aria-label={`${key}地址`} value={value} placeholder="服务地址(只保存,不连接)" onChange={e => settings({ services: { ...draft.settings.services, [key]: e.target.value } })}/></div>)}<p className="d-foot">真实麦克风和摄像头未启用。视觉窗只允许模拟状态,观察过期不当作眼前。</p></>}
{!real && section === 'voice' && <><Off title="演示里不录音,也不上传。" will="接上真实服务以后:上传或录一段参考声音 → 试听她用这个声音说话 → 给她之后的通话用。只换声音,名字、底色、关系、聊天和记忆都不变。" now="演示里不会请求麦克风,也不会发出任何网络请求。"/><div className="field"><div className="seg" role="group" aria-label="参考声音来源"><button disabled>上传音频文件</button><button disabled>现在录一段</button></div></div></>}
{real && open && <div hidden={section !== 'voice'}><VoiceSection name={state.identity.name} active={section === 'voice'} onDirty={setVoiceDirty} onCap={setVoiceCap}/></div>}
{section === 'display' && <><div className="opt-row">{(['moon', 'fog'] as Theme[]).map(t => <button className="opt" data-t={t} key={t} aria-pressed={theme === t} onClick={() => setTheme(t)}><div className="sw"/><b>{t === 'moon' ? '靛蓝月光' : '蓝紫雾光'}</b><span>立即切换,保留你的选择</span></button>)}</div><label className="switch-row"><span>减少动效<small>镜头不推近,只做淡入淡出;循环动画停下</small></span><input type="checkbox" className="switch" checked={draft.settings.reduced} onChange={e => settings({ reduced: e.target.checked })}/></label><p className="d-foot">也会自动尊重系统的减少动效设置。切到其他网页时暂停背景动画。</p></>}
{real && section === 'city' && <><Off title="城市与天气还没有接上。" will="接上以后,你选一个真实城市,她房间里的天气、白天黑夜和作息都跟着那里走;换城市不需要每次重新定位。" now="现在窗外的雨是界面氛围,不是真实天气。尚未设置可核实的城市,天气来源尚未确定。"/><Field label="搜索城市" hint="可浏览候选目录;当前无法保存,不会更改她的城市。"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button disabled>{c}<small>候选城市 · 保存待接入</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <div className="empty">当前目录没有匹配的城市。</div>}<div className="actions"><Button disabled>保存城市 · 待接入</Button></div></>}
{real && section === 'appearance' && <><dl className="kv"><dt>现在的样子</dt><dd>工程外观 v2<small>参考静帧 · 尚无成套日常与交谈视频</small></dd></dl><Off title="换外观还没有接上。" will="接上以后:选择素材包 → 检查素材 → 看新旧对比 → 确认「她还是她」。只换样子,名字、底色、记忆和关系都不变。" now="素材包规范与导入检查尚未定稿。这里不会导入、预览或替换任何素材。"/><Field label="选择外观素材包" hint="素材包格式与媒体检查将在后续接入。当前不上传、不读取文件。"><input type="file" disabled/></Field><ul className="phases">{['清单结构与版本', '媒体格式与时长', '人物一致性', '必要场景覆盖', '可用性与兼容性'].map(label => <li key={label}>待检查 · {label}</li>)}</ul><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前内置参考静帧"/><figcaption>当前参考</figcaption></figure><figure><div className="empty">导入并通过检查后显示新外观</div><figcaption>新旧对比 · 待接入</figcaption></figure></div><Button disabled>确认应用外观 · 待接入</Button></>}
+221
View File
@@ -0,0 +1,221 @@
// ── 她的声音 (CG-010 v1.12, HEL-900): reference → fresh preview → apply, inside the approved settings pane. ──
// Your reference and her synthesized preview are labelled apart and never stand in for each other. Every request and
// every audio URL belongs to one generation; switching voice, retrying, leaving or a late answer throws the old one away
// (request aborted, audio stopped, object URL revoked), so an old sample can never pass for the new one.
import { useEffect, useRef, useState, type RefObject } from 'react';
import { clockOf } from '../adapters/real';
import { applyVoice, LABEL_MAX, listVoices, PREVIEW_DEFAULT, PREVIEW_MAX, previewVoice, Recorder, registerVoice, SAY, SUGGEST_MAX, SUGGEST_MIN, TEXT_MAX, toReference, VoiceError, type CustomVoice, type RecView, type VoiceSelection } from '../voice/custom';
import { Button, Field, Icon, Status } from '../shared/ui';
export type VoiceCap = 'edit' | 'off' | 'unknown';
type Load = { state: 'loading' } | { state: 'ok'; voices: CustomVoice[]; selection: VoiceSelection } | { state: 'off'; text: string } | { state: 'error'; text: string };
interface Take { wav: Blob; url: string; seconds: number; from: 'file' | 'record'; name: string }
interface Sample { voice: string; url: string; state: 'loading' | 'ready' | 'error' }
const message = (e: unknown) => e instanceof VoiceError ? e.message : SAY.failed;
const secs = (s: number) => `${s.toFixed(1)} 秒`;
const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
// A small themed player instead of the browser's grey bar; the <audio> under it does the playing and reports canplay.
function Pill({ src, label, auto = false, tone, audio, onReady, onBroken }: { src: string; label: string; auto?: boolean; tone: 'ref' | 'her'; audio: RefObject<HTMLAudioElement>; onReady?: () => void; onBroken?: () => void }) {
const [playing, setPlaying] = useState(false), [at, setAt] = useState(0), [length, setLength] = useState(0);
return <div className={`pill ${tone} ${playing ? 'on' : ''}`} role="group" aria-label={label}>
<audio ref={audio} src={src} preload="auto" autoPlay={auto} onCanPlay={onReady} onError={onBroken} onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)} onTimeUpdate={e => setAt(e.currentTarget.currentTime)} onLoadedMetadata={e => setLength(Number.isFinite(e.currentTarget.duration) ? e.currentTarget.duration : 0)}/>
<button className="pill-play" aria-label={playing ? `暂停${label}` : `播放${label}`} onClick={() => { const a = audio.current; if (!a) return; if (a.paused) void a.play().catch(() => {}); else a.pause(); }}><Icon name={playing ? 'pause' : 'play'}/></button>
<span className="pill-track" aria-hidden="true"><i style={{ transform: `scaleX(${length ? Math.min(1, at / length) : 0})` }}/></span>
<span className="pill-time">{clock(at)} / {clock(length)}</span>
</div>;
}
export function VoiceSection({ name, active, onDirty, onCap }: { name: string; active: boolean; onDirty: (dirty: boolean) => void; onCap: (cap: VoiceCap) => void }) {
const [load, setLoad] = useState<Load>({ state: 'loading' }), [reads, setReads] = useState(0), [seen, setSeen] = useState(active);
const [from, setFrom] = useState<'file' | 'record'>('file'), [rec, setRec] = useState<RecView>({ phase: 'idle', seconds: 0 });
const [take, setTake] = useState<Take | null>(null), [form, setForm] = useState({ label: '', text: '', allowAsr: false });
const [registering, setRegistering] = useState(false), [regNote, setRegNote] = useState<{ text: string; error: boolean }>({ text: '', error: false });
const [candidate, setCandidate] = useState(''), [line, setLine] = useState(''), [sample, setSample] = useState<Sample | null>(null);
const [applying, setApplying] = useState(false), [note, setNote] = useState<{ text: string; error: boolean }>({ text: '', error: false });
const fileInput = useRef<HTMLInputElement>(null), player = useRef<HTMLAudioElement>(null), refPlayer = useRef<HTMLAudioElement>(null);
// One controller per kind of request; a new one aborts the old. `takeGen` guards decoding a file or a recording.
const ctl = useRef<Record<'list' | 'register' | 'preview' | 'apply', AbortController | null>>({ list: null, register: null, preview: null, apply: null });
const takeGen = useRef(0), urls = useRef(new Set<string>()), listed = useRef(false);
const fresh = (kind: keyof typeof ctl.current) => { ctl.current[kind]?.abort(); const c = new AbortController(); ctl.current[kind] = c; return c; };
const own = (blob: Blob) => { const url = URL.createObjectURL(blob); urls.current.add(url); return url; };
const drop = (url?: string) => { if (url && urls.current.delete(url)) URL.revokeObjectURL(url); };
const recorder = useRef<Recorder | null>(null);
recorder.current ??= new Recorder({ view: setRec, done: blob => void accept(blob, 'record', '这次录音'), fail: text => setRegNote({ text, error: true }) });
// Everything this section holds goes with it: requests, microphone, audio and every object URL.
useEffect(() => () => {
recorder.current?.cancel();
Object.values(ctl.current).forEach(c => c?.abort());
takeGen.current++;
for (const url of urls.current) URL.revokeObjectURL(url);
urls.current.clear();
}, []);
// Out of sight is out of use: the microphone closes and nothing keeps playing. A finished take stays for later.
useEffect(() => {
if (active) { setSeen(true); return; }
if (recorder.current?.busy && recorder.current.view.phase !== 'converting') { recorder.current.cancel(); setRegNote({ text: '离开了这里,录音已停止并丢弃,麦克风已关闭。', error: false }); }
player.current?.pause(); refPlayer.current?.pause();
}, [active]);
useEffect(() => { onDirty(!!take); return () => onDirty(false); }, [take, onDirty]);
// Read the list the first time the section is opened (and on retry). Reading never touches the microphone.
useEffect(() => {
if (!seen) return;
const c = fresh('list');
setLoad(l => l.state === 'ok' ? l : { state: 'loading' });
listVoices(c.signal).then(list => {
if (c.signal.aborted) return;
if (!list.configured) { setLoad({ state: 'off', text: SAY.notConfigured }); onCap('off'); return; }
listed.current = true; setNote(n => n.error ? { text: '', error: false } : n); setLoad({ state: 'ok', voices: list.voices, selection: list.selection }); onCap('edit');
}, e => {
if (c.signal.aborted) return;
const status = e instanceof VoiceError ? e.status : 0;
if (status === 404 || status === 405) { setLoad({ state: 'off', text: SAY.noRoute }); onCap('off'); return; }
// A list already on screen stays usable; only the first read turns into the retry card.
if (listed.current) { setNote({ text: message(e), error: true }); return; }
setLoad({ state: 'error', text: message(e) }); onCap('unknown');
});
// eslint-disable-next-line react-hooks/exhaustive-deps -- re-read only on first sight and explicit retries.
}, [seen, reads]);
async function accept(input: Blob, kind: 'file' | 'record', label: string) {
const gen = ++takeGen.current;
setRegNote({ text: kind === 'file' ? '正在读取并转成 WAV…' : '', error: false });
try {
const ref = await toReference(input);
if (gen !== takeGen.current) return;
const url = own(ref.wav);
setTake(old => { drop(old?.url); return { wav: ref.wav, url, seconds: ref.seconds, from: kind, name: label }; });
setRegNote({ text: '', error: false });
} catch (e) {
if (gen !== takeGen.current) return;
setRegNote({ text: message(e), error: true });
} finally { if (gen === takeGen.current) recorder.current?.settled(); }
}
function chooseFile(file?: File) {
if (fileInput.current) fileInput.current.value = '';
if (!file || registering) return;
void accept(file, 'file', file.name.slice(0, 60));
}
function discardTake() { takeGen.current++; recorder.current?.cancel(); setTake(old => { drop(old?.url); return null; }); setRegNote({ text: '', error: false }); }
function switchFrom(next: 'file' | 'record') { if (next === from) return; recorder.current?.cancel(); setFrom(next); setRegNote({ text: '', error: false }); }
const text = form.text.trim(), needText = !text && !form.allowAsr;
async function register() {
// A second tap before the first answer is ignored (not a replacement): the first upload may already be on the server.
if (!take || ctl.current.register || needText) return;
const c = fresh('register'), sent = take;
setRegistering(true); setRegNote({ text: form.allowAsr && !text ? '正在登记,并让服务器把这段声音转写成文字…' : '正在登记这段声音…', error: false });
try {
const done = await registerVoice(sent.wav, form, c.signal);
if (c.signal.aborted) return;
setTake(old => { if (old === sent) { drop(old.url); return null; } return old; });
setForm({ label: '', text: '', allowAsr: false });
setRegNote({ text: done.prompt_text_source === 'asr' ? `登记好了:「${done.label}」。服务器转写的参考文字是:${done.prompt_text || '(空)'}` : `登记好了:「${done.label}」。`, error: false });
setLoad(l => l.state === 'ok' && !l.voices.some(v => v.id === done.id) ? { ...l, voices: [...l.voices, { id: done.id, label: done.label, source: 'custom', selected: false, previewed: false, registered_at: Date.now() }] } : l);
pick(done.id, `先听听${name}用「${done.label}」说话,再决定要不要给她用。`);
setReads(n => n + 1);
} catch (e) {
if (c.signal.aborted) return;
// Nothing is lost on failure: the take, the label and the text all stay for another try.
setRegNote({ text: message(e), error: true });
} finally { if (ctl.current.register === c) { ctl.current.register = null; setRegistering(false); } }
}
// Choosing another voice retires the sample of the previous one at once.
function pick(id: string, say = '') {
ctl.current.preview?.abort(); ctl.current.preview = null;
player.current?.pause();
setSample(old => { drop(old?.url); return null; });
setCandidate(id); setNote({ text: say, error: false });
}
async function preview() {
if (!candidate) return;
const c = fresh('preview'), voice = candidate;
player.current?.pause();
setSample(old => { drop(old?.url); return { voice, url: '', state: 'loading' }; });
setNote({ text: '正在用这个声音现场合成…', error: false });
try {
const wav = await previewVoice(voice, line, c.signal);
if (c.signal.aborted) return;
// Shown only once the browser has really loaded it (canplay); until then it is not "heard".
const url = own(wav);
setSample({ voice, url, state: 'loading' });
} catch (e) {
if (c.signal.aborted) return;
setSample(null); setNote({ text: message(e), error: true });
}
}
const playable = (url: string) => { setSample(s => s && s.url === url && s.state === 'loading' ? { ...s, state: 'ready' } : s); setNote(n => n.error ? n : { text: '', error: false }); };
const unplayable = (url: string) => { setSample(s => { if (!s || s.url !== url) return s; drop(url); return null; }); setNote({ text: SAY.unplayable, error: true }); };
async function apply() {
if (!candidate || ctl.current.apply || sample?.voice !== candidate || sample.state !== 'ready') return;
const c = fresh('apply'), voice = candidate;
setApplying(true); setNote({ text: '正在给她换上…', error: false });
try {
const selection = await applyVoice(voice, c.signal);
if (c.signal.aborted) return;
setLoad(l => l.state === 'ok' ? { ...l, selection, voices: l.voices.map(v => ({ ...v, selected: v.id === voice, previewed: v.previewed || v.id === voice })) } : l);
setNote({ text: `好了,${name}之后的通话会用「${selection.label || voice}」。已经接通的通话不会中途换声。名字、底色、关系、聊天和记忆都没有变。`, error: false });
} catch (e) {
if (c.signal.aborted) return;
setNote({ text: message(e), error: true });
} finally { if (ctl.current.apply === c) { ctl.current.apply = null; setApplying(false); } }
}
if (load.state === 'loading') return <div className="skel" aria-hidden="true">{[70, 54, 62].map(w => <i key={w} style={{ width: `${w}%` }}/>)}</div>;
if (load.state === 'off') return <div className="off-card"><p className="off-t">{load.text}</p><p>接上以后:上传或录一段参考声音 → 试听{name}用它说话 → 给她用。只换声音,名字、底色、关系、聊天和记忆都不变。</p><p className="d-dim">这里不会请求麦克风,也不会上传任何声音。</p></div>;
if (load.state === 'error') return <div className="off-card" role="alert"><p className="off-t">声音列表一时没读出来。</p><p>{load.text}</p><Button onClick={() => setReads(n => n + 1)}>再试一次</Button></div>;
const { voices, selection } = load, current = voices.find(v => v.id === selection.voice);
const mine = voices.filter(v => v.source === 'custom'), builtin = voices.filter(v => v.source === 'builtin');
const chosen = voices.find(v => v.id === candidate), ready = sample?.voice === candidate && sample.state === 'ready';
const recording = rec.phase === 'asking' || rec.phase === 'recording';
const row = (v: CustomVoice) => <li key={v.id}><button aria-pressed={candidate === v.id} onClick={() => pick(v.id)} disabled={applying}><span>{v.label}{v.selected && <span className="tag accent">正在用</span>}</span><small>{v.source === 'custom' ? `自定义${v.registered_at ? ` · ${clockOf(v.registered_at).date}` : ''}` : '服务自带'}{v.previewed ? ' · 试听过' : ''}</small></button></li>;
return <div className="voice-sec">
<dl className="kv"><dt>现在的声音</dt><dd>{selection.voice ? <>{current?.label || selection.label || selection.voice}<small>{current?.source === 'custom' ? '自定义' : current ? '服务自带' : '这个声音已不在列表里,通话时会用默认声音'}{selection.updated_at ? ` · ${clockOf(selection.updated_at).date} ${clockOf(selection.updated_at).time} 换上` : ''}</small></> : <>还没有为她选过<small>通话时用服务默认的声音</small></>}</dd>
<dt>什么时候生效</dt><dd>下一次通话<small>已经接通的通话不会中途换声</small></dd></dl>
<h4 className="sub-h">给一段参考声音<small>{SUGGEST_MIN}–{SUGGEST_MAX} 秒 · 安静的地方 · 念一两句完整的话</small></h4>
<div className="field"><div className="seg" role="group" aria-label="参考声音来源">{([['file', '上传音频文件'], ['record', '现在录一段']] as const).map(([k, label]) => <button key={k} aria-pressed={from === k} disabled={registering || rec.phase === 'converting'} onClick={() => switchFrom(k)}>{label}</button>)}</div></div>
{from === 'file' ? <div className="field file-pick"><label className={`btn-ghost sm ${registering ? 'is-disabled' : ''}`}><Icon name="up"/>选择音频文件<input ref={fileInput} type="file" accept=".wav,audio/wav,audio/*" disabled={registering} onChange={e => chooseFile(e.target.files?.[0])}/></label><small>WAV 最稳妥;其他格式要看这个浏览器能不能解开,解不开会直接说明。会转成 16kHz 单声道 WAV,只登记到这台服务器。</small></div>
: <div className={`rec card ${recording ? 'on' : ''}`} data-phase={rec.phase}>
{rec.phase === 'idle' && <><Button onClick={() => { setRegNote({ text: '', error: false }); void recorder.current?.start(); }} disabled={registering}><Icon name="mic"/>开始录音</Button><p className="d-dim">点了才会请求麦克风,只录声音。停止、取消或离开这里,麦克风马上关闭。最长 {SUGGEST_MAX} 秒,到时自动停。</p></>}
{rec.phase === 'asking' && <><p className="rec-line" role="status"><i className="rec-dot"/>正在请求麦克风…</p><Button onClick={() => recorder.current?.cancel()}>取消</Button></>}
{rec.phase === 'recording' && <><p className="rec-line" role="status" aria-live="off"><i className="rec-dot"/>正在录音 · 麦克风开着<b>{clock(rec.seconds)} / {clock(SUGGEST_MAX)}</b></p><div className="rec-bar" aria-hidden="true"><i style={{ transform: `scaleX(${Math.min(1, rec.seconds / SUGGEST_MAX)})` }}/><em style={{ left: `${SUGGEST_MIN / SUGGEST_MAX * 100}%` }}/></div><div className="rec-acts"><Button primary onClick={() => recorder.current?.stop()}><Icon name="stop"/>停止,用这段</Button><Button onClick={() => { recorder.current?.cancel(); setRegNote({ text: '录音已取消并丢弃,麦克风已关闭。', error: false }); }}>取消</Button></div></>}
{rec.phase === 'converting' && <p className="rec-line" role="status">麦克风已关闭 · 正在转成 WAV…</p>}
</div>}
{take && <div className="card take">
<h4><Icon name="user"/>参考原声 · 你给的声音,不是{name}的声音</h4>
<Pill key={take.url} src={take.url} label="参考原声" tone="ref" audio={refPlayer}/>
<p className="d-dim">{take.from === 'record' ? '这次录音' : take.name} · 已转为 WAV · 16kHz 单声道 16 位 · {secs(take.seconds)}{take.seconds < SUGGEST_MIN ? ` · 偏短,建议 ${SUGGEST_MIN} 秒以上` : take.seconds > SUGGEST_MAX ? ` · 偏长,建议 ${SUGGEST_MAX} 秒以内` : ''}</p>
<Field label="给这个声音起个名字" hint={`最多 ${LABEL_MAX} 个字,只用来在这里区分;不填就用编号。`}><input className="input" value={form.label} maxLength={LABEL_MAX} placeholder="比如:轻一点的她" disabled={registering} onChange={e => setForm(f => ({ ...f, label: e.target.value.replace(/[<>\p{Cc}]/gu, '') }))}/></Field>
<Field label="参考文字" hint="这段声音里念的原话。写得越准,克隆越像。"><textarea className="textarea" value={form.text} maxLength={TEXT_MAX} rows={2} disabled={registering} placeholder="照着录音里念的内容写下来" onChange={e => setForm(f => ({ ...f, text: e.target.value }))}/></Field>
<label className="switch-row"><span>参考文字留空时,允许服务器转写<small>{text ? '已经填写了参考文字,不会转写。' : '会用这台服务器上的语音识别听一遍这段声音;不打开就必须填写参考文字。'}</small></span><input type="checkbox" className="switch" checked={form.allowAsr && !text} disabled={!!text || registering} onChange={e => setForm(f => ({ ...f, allowAsr: e.target.checked }))}/></label>
<div className="take-acts"><Button primary disabled={registering || needText} onClick={() => void register()}>{registering ? '正在登记…' : '登记这段声音'}</Button><Button disabled={registering} onClick={discardTake}>换一段</Button></div>
{needText && !registering && <p className="d-dim">填写参考文字,或打开上面的转写开关,才能登记。</p>}
</div>}
<Status text={regNote.text} error={regNote.error}/>
<h4 className="sub-h">可以给她用的声音<small>先试听,再给她用</small></h4>
<p className="voice-group">你给的声音</p>
{mine.length ? <ul className="city-list voice-list">{mine.map(row)}</ul> : <div className="empty sm">还没有登记过自己的声音。</div>}
{builtin.length > 0 && <details className="voice-builtin" open={!!chosen && chosen.source === 'builtin'}><summary>服务自带的声音 · {builtin.length} 个</summary><ul className="city-list voice-list">{builtin.map(row)}</ul></details>}
{chosen && <div className="card audition" aria-live="polite">
<h4><Icon name="sparkle"/>试听 · {chosen.label}</h4>
<Field label="试听这句话" hint={`可以换成你想听的话,最多 ${PREVIEW_MAX} 个字。每次都是现场合成,不拿旧的冒充。`}><input className="input" value={line} maxLength={PREVIEW_MAX} placeholder={PREVIEW_DEFAULT} onChange={e => setLine(e.target.value)}/></Field>
<div className="take-acts"><Button disabled={sample?.state === 'loading' || applying} onClick={() => void preview()}>{sample?.state === 'loading' ? '正在现场合成…' : sample ? '再听一次' : '生成试听'}</Button>
{chosen.selected ? <span className="tag accent">她现在就用这个</span> : <Button primary disabled={!ready || applying} onClick={() => void apply()}>{applying ? '正在换上…' : `给${name}用这个声音`}</Button>}</div>
{sample?.url && <figure className={`sample ${ready ? 'ready' : ''}`}><Pill key={sample.url} src={sample.url} label="试听" tone="her" auto audio={player} onReady={() => playable(sample.url)} onBroken={() => unplayable(sample.url)}/><figcaption>{name}用「{chosen.label}」说的 · 刚刚现场合成 · 不是参考原声</figcaption></figure>}
{!ready && !chosen.selected && <p className="d-dim">听过这次现场合成的试听,才能给她用。</p>}
</div>}
<Status text={note.text} error={note.error}/>
<p className="d-foot">换声音只换她说话的声音:名字、出生底色、关系、聊天和记忆都不变,也不会重新创建她。声音登记在这台服务器上;暂时不能在这里删除登记过的声音。</p>
</div>;
}
+44
View File
@@ -990,4 +990,48 @@ body.creating .now-chip{display:none}
.rel-cards{grid-template-columns:1fr}
.seg button{padding:0 12px;font-size:13px}
.derived{grid-template-columns:1fr}
}
/* ── 她的声音 (HEL-900): reference → fresh preview → apply, inside the settings pane. Tokens only; both themes follow. ── */
.voice-sec .card h4{letter-spacing:.06em}
.voice-sec .pill{display:flex;align-items:center;gap:12px;height:44px;padding:0 14px 0 5px;margin:2px 0 6px;border-radius:var(--radius-pill);background:var(--field);border:1px solid var(--field-line);transition:border-color var(--dur-ui) var(--ease-out),box-shadow var(--dur-ui) var(--ease-out)}
.voice-sec .pill audio{display:none}
.voice-sec .pill.on{border-color:color-mix(in srgb,var(--accent) 45%,transparent);box-shadow:0 0 16px -8px var(--accent-glow)}
.pill-play{flex:none;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;color:var(--text-1);background:rgba(255,255,255,.07);transition:background-color var(--dur-ui) var(--ease-out),color var(--dur-ui) var(--ease-out)}
.pill.her .pill-play{color:var(--on-accent);background:var(--accent);box-shadow:0 0 14px -4px var(--accent-glow)}
.pill-play .ico{width:15px;height:15px}
.pill-track{position:relative;flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.08);overflow:hidden}
.pill-track i{position:absolute;inset:0;transform-origin:left;background:var(--text-2);transition:transform 250ms linear}
.pill.her .pill-track i{background:var(--accent)}
.pill-time{flex:none;font-family:var(--font-num);font-size:12px;color:var(--text-3);font-variant-numeric:tabular-nums}
.file-pick label{position:relative;cursor:pointer}
.file-pick label.is-disabled{opacity:.5;pointer-events:none}
.file-pick input[type=file]{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}
.file-pick:focus-within label{outline:2px solid var(--accent);outline-offset:2px}.voice-sec .take-acts,.voice-sec .rec-acts{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-top:6px}
.voice-sec .take .switch-row{border-top:0;padding:4px 0 10px}
.voice-sec .rec{display:flex;flex-direction:column;align-items:flex-start;gap:10px;transition:border-color var(--dur-ui) var(--ease-out),box-shadow var(--dur-ui) var(--ease-out)}
.voice-sec .rec .d-dim{margin:0}
.voice-sec .rec.on{border-color:color-mix(in srgb,var(--accent) 45%,transparent);box-shadow:0 0 22px -10px var(--accent-glow)}
.rec-line{display:flex;align-items:center;gap:10px;font-size:14.5px;color:var(--text-1)}
.rec-line b{font-family:var(--font-num);font-weight:400;color:var(--text-2);font-variant-numeric:tabular-nums;margin-left:4px}
.rec-dot{width:9px;height:9px;border-radius:50%;background:var(--danger);box-shadow:0 0 10px var(--danger);animation:dotPulse 1.2s var(--ease-in-out) infinite}
.rec[data-phase="asking"] .rec-dot{background:var(--text-3);box-shadow:none}
.rec-bar{position:relative;width:100%;height:4px;border-radius:2px;background:var(--field);overflow:hidden}
.rec-bar i{position:absolute;inset:0;transform-origin:left;background:var(--accent);box-shadow:0 0 8px var(--accent-glow);transition:transform 200ms linear}
.rec-bar em{position:absolute;top:0;bottom:0;width:1px;background:var(--text-3)}
.voice-group{font-size:12.5px;color:var(--text-3);margin:0 0 6px}
.voice-list li button > span{display:inline-flex;align-items:center;gap:8px}
.voice-list li button:disabled{opacity:.6}
.voice-sec .empty.sm{padding:14px 12px;font-size:13.5px;border:1px dashed var(--field-line);border-radius:14px}
.voice-builtin{margin:12px 0 16px}
.voice-builtin summary{cursor:pointer;font-size:13.5px;color:var(--text-2);padding:6px 2px;list-style-position:inside}
.voice-builtin summary:hover{color:var(--text-1)}
.voice-sec .audition{margin-top:16px;animation:detail-in var(--dur-ui) var(--ease-out)}
.voice-sec .sample{margin:12px 0 4px;padding:10px 12px;border-radius:14px;border:1px solid var(--field-line);opacity:.55;transition:opacity var(--dur-ui) var(--ease-out),border-color var(--dur-ui) var(--ease-out),box-shadow var(--dur-ui) var(--ease-out)}
.voice-sec .sample.ready{opacity:1;border-color:color-mix(in srgb,var(--accent) 50%,transparent);box-shadow:0 0 18px -8px var(--accent-glow)}
.voice-sec .sample figcaption{font-size:12px;color:var(--text-3)}
.voice-sec .take .ico,.voice-sec .audition .ico{width:14px;height:14px}
.voice-sec .btn-ghost .ico,.voice-sec .btn-primary .ico{width:16px;height:16px}
@media (max-width:720px){
.voice-sec .take-acts .btn-primary,.voice-sec .take-acts .btn-ghost,.voice-sec .rec-acts button{flex:1}
.voice-sec .rec .btn-ghost{width:100%}
}
+249
View File
@@ -0,0 +1,249 @@
// ── Her own voice (CG-010 v1.12, HEL-900): give a reference recording, hear her say something with it, apply it. ──
// Contract: docs/voice-custom-contract-HEL899.md §2. Everything goes through the same-origin API; the page never talks to
// the voice panel or TTS itself and holds no credentials. Registration takes raw PCM WAV bytes, so whatever the browser
// recorded or the file it was given is decoded here and written out again as 16 kHz mono 16-bit WAV — a WebM renamed to
// .wav is not a WAV. The reference you gave and her synthesized preview are separate things and are never swapped.
export interface CustomVoice { id: string; label: string; source: 'builtin' | 'custom'; selected: boolean; previewed: boolean; registered_at: number | null }
export interface VoiceSelection { voice: string | null; label: string; updated_at: number | null }
export type VoiceList = { configured: false } | { configured: true; voices: CustomVoice[]; selection: VoiceSelection };
export interface Registered { id: string; label: string; prompt_text: string; prompt_text_source: 'user' | 'asr' }
export const RATE = 16000;
export const MIN_SECONDS = 2, SUGGEST_MIN = 5, SUGGEST_MAX = 20, MAX_BYTES = 15 * 1024 * 1024;
// Bigger files are refused before decoding (memory); the server's own line is 15 MB of WAV.
export const MAX_INPUT_BYTES = 50 * 1024 * 1024;
export const LABEL_MAX = 20, TEXT_MAX = 500, PREVIEW_MAX = 200;
export const PREVIEW_DEFAULT = '你好,这是我的声音,以后就用它陪你说话。';
export const SAY = {
noRoute: '这台服务还没有自定义声音的通路。文字和现有语音不受影响。',
notConfigured: '语音还没有在这台服务上配置,暂时不能换声音。文字仍可使用。',
offline: '网络断开了。你给的声音和填写的内容都还在,连上后可以再试。',
unreachable: '暂时连不上服务器。你给的声音和填写的内容都还在,可以再试。',
odd: '服务器这次没有正确响应,请稍后再试。',
failed: '这次没有完成,请稍后再试。',
tooShort: '这段太短了(至少 2 秒),请录 5–20 秒、念一两句完整的话。',
tooBig: '这段声音太大了,请选 5–20 秒的一段。',
fileTooBig: '这个文件太大了,请选 5–20 秒的一段。',
undecodable: '这个浏览器解不开这段音频,没法转成 WAV。可以换一个 WAV 文件,或在这里直接录一段。',
silent: '这段几乎没有声音,请靠近麦克风再录一次。',
badPreview: '这次试听的结果不是可播放的声音,没有拿来播放。可以再试一次。',
unplayable: '这段试听在这个浏览器里播不出来,没有当作试过。可以再试一次。',
denied: '没有拿到麦克风权限,没有开始录音。可以改用上传文件。',
noMic: '没有找到可用的麦克风。可以改用上传文件。',
micBusy: '麦克风被别的程序占用了,没有开始录音。',
insecure: '这个地址不是安全连接,浏览器不允许使用麦克风。可以改用上传文件,或从 HTTPS 入口打开。',
noRecorder: '这个浏览器不支持在网页里录音。可以改用上传文件。',
micGone: '麦克风被关掉了,这段没有录完,已经丢弃。',
recordFailed: '这次录音没有成功,已经丢弃,可以再录一次。',
} as const;
export class VoiceError extends Error { constructor(message: string, readonly status = 0) { super(message); } }
// ── WAV ──
export function encodeWav(samples: Float32Array, rate = RATE): ArrayBuffer {
const out = new ArrayBuffer(44 + samples.length * 2), v = new DataView(out);
const text = (at: number, s: string) => { for (let i = 0; i < s.length; i++) v.setUint8(at + i, s.charCodeAt(i)); };
text(0, 'RIFF'); v.setUint32(4, 36 + samples.length * 2, true); text(8, 'WAVE');
text(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true);
text(36, 'data'); v.setUint32(40, samples.length * 2, true);
for (let i = 0; i < samples.length; i++) { const s = Math.max(-1, Math.min(1, samples[i])); v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true); }
return out;
}
export interface WavInfo { rate: number; channels: number; bits: number; seconds: number }
// Reads the header the way the server checks it (RIFF/WAVE, fmt and data chunks). Anything else is not a WAV.
export function wavInfo(buf: ArrayBuffer): WavInfo | null {
if (buf.byteLength < 44) return null;
const v = new DataView(buf), tag = (at: number) => String.fromCharCode(v.getUint8(at), v.getUint8(at + 1), v.getUint8(at + 2), v.getUint8(at + 3));
if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return null;
let at = 12, fmt: Omit<WavInfo, 'seconds'> | null = null;
while (at + 8 <= buf.byteLength) {
const id = tag(at), size = v.getUint32(at + 4, true);
if (id === 'fmt ' && size >= 16 && at + 24 <= buf.byteLength) fmt = { channels: v.getUint16(at + 10, true), rate: v.getUint32(at + 12, true), bits: v.getUint16(at + 22, true) };
if (id === 'data') {
if (!fmt || !fmt.rate || !fmt.channels || !fmt.bits) return null;
const bytes = Math.min(size, buf.byteLength - at - 8);
return { ...fmt, seconds: bytes / (fmt.rate * fmt.channels * (fmt.bits / 8)) };
}
at += 8 + size + (size & 1);
}
return null;
}
export interface Decoded { sampleRate: number; length: number; numberOfChannels: number; getChannelData(channel: number): Float32Array }
export function mixdown(buf: Decoded): Float32Array {
const out = new Float32Array(buf.length), n = buf.numberOfChannels;
for (let c = 0; c < n; c++) { const d = buf.getChannelData(c); for (let i = 0; i < out.length; i++) out[i] += d[i] / n; }
return out;
}
// Decodes with the browser's own decoder, resampled to 16 kHz by an offline context (no device, nothing to close).
export function browserDecode(data: ArrayBuffer): Promise<Decoded> {
const Offline = (globalThis as { OfflineAudioContext?: typeof OfflineAudioContext }).OfflineAudioContext;
if (!Offline) return Promise.reject(new VoiceError(SAY.undecodable));
return new Offline(1, 1, RATE).decodeAudioData(data);
}
export interface Reference { wav: Blob; seconds: number }
// Any audio the browser can decode → the WAV the server accepts. Refuses what the server would refuse anyway.
export async function toReference(input: Blob, decode: (data: ArrayBuffer) => Promise<Decoded> = browserDecode): Promise<Reference> {
if (input.size > MAX_INPUT_BYTES) throw new VoiceError(SAY.fileTooBig);
let decoded: Decoded;
try { decoded = await decode(await input.arrayBuffer()); } catch { throw new VoiceError(SAY.undecodable); }
let samples = mixdown(decoded);
if (decoded.sampleRate !== RATE) samples = resample(samples, decoded.sampleRate, RATE);
const seconds = samples.length / RATE;
if (seconds < MIN_SECONDS) throw new VoiceError(SAY.tooShort);
if (!samples.some(s => Math.abs(s) > 0.003)) throw new VoiceError(SAY.silent);
const wav = encodeWav(samples, RATE);
if (wav.byteLength > MAX_BYTES) throw new VoiceError(SAY.tooBig);
return { wav: new Blob([wav], { type: 'audio/wav' }), seconds };
}
// Only used when a decoder ignored the requested rate; linear is enough for a reference prompt.
export function resample(input: Float32Array, from: number, to: number): Float32Array {
const out = new Float32Array(Math.floor(input.length * to / from)), step = from / to;
for (let i = 0; i < out.length; i++) { const x = i * step, j = Math.floor(x), f = x - j; out[i] = (input[j] ?? 0) * (1 - f) + (input[j + 1] ?? input[j] ?? 0) * f; }
return out;
}
// ── API (same origin) ──
type Fetch = typeof fetch;
const online = () => typeof navigator === 'undefined' || navigator.onLine !== false;
async function call(f: Fetch, path: string, init: RequestInit): Promise<Response> {
if (!online()) throw new VoiceError(SAY.offline);
try { return await f(`/api/voice/${path}`, init); }
catch (e) { if (init.signal?.aborted) throw e; throw new VoiceError(online() ? SAY.unreachable : SAY.offline); }
}
async function refusal(r: Response, fallback: string = SAY.failed): Promise<VoiceError> {
const data = await r.json().catch(() => null) as { detail?: unknown } | null;
return new VoiceError(typeof data?.detail === 'string' && data.detail ? data.detail : fallback, r.status);
}
const voiceItem = (v: unknown): v is CustomVoice => { const x = v as Record<string, unknown>; return !!x && typeof x === 'object' && typeof x.id === 'string' && /^[\w-]{1,40}$/u.test(x.id) && typeof x.label === 'string' && (x.source === 'builtin' || x.source === 'custom'); };
function selectionOf(v: unknown): VoiceSelection {
const s = v as Record<string, unknown> | null;
return { voice: typeof s?.voice === 'string' && s.voice ? s.voice : null, label: typeof s?.label === 'string' ? s.label : '', updated_at: Number.isFinite(s?.updated_at) ? s!.updated_at as number : null };
}
export async function listVoices(signal: AbortSignal, f: Fetch = fetch): Promise<VoiceList> {
const r = await call(f, 'voices', { signal });
// A server from before HEL-899 has no such route: "not wired", not a failure.
if (r.status === 404 || r.status === 405) throw new VoiceError(SAY.noRoute, r.status);
if (!r.ok) throw await refusal(r);
const data = await r.json().catch(() => null) as { configured?: unknown; voices?: unknown; selection?: unknown } | null;
if (!data || typeof data !== 'object') throw new VoiceError(SAY.odd);
if (data.configured !== true) return { configured: false };
const voices = (Array.isArray(data.voices) ? data.voices : []).filter(voiceItem).map(v => ({ id: v.id, label: v.label || v.id, source: v.source, selected: v.selected === true, previewed: v.previewed === true, registered_at: Number.isFinite(v.registered_at) ? v.registered_at : null }));
return { configured: true, voices, selection: selectionOf(data.selection) };
}
export async function registerVoice(wav: Blob, form: { label: string; text: string; allowAsr: boolean }, signal: AbortSignal, f: Fetch = fetch): Promise<Registered> {
const q = new URLSearchParams({ label: form.label.trim(), prompt_text: form.text.trim(), allow_asr: form.allowAsr && !form.text.trim() ? 'true' : 'false' });
const r = await call(f, `voices?${q}`, { method: 'POST', headers: { 'Content-Type': 'audio/wav' }, body: wav, signal });
if (!r.ok) throw await refusal(r);
const data = await r.json().catch(() => null) as Partial<Registered> | null;
if (!data || typeof data.id !== 'string' || !data.id) throw new VoiceError(SAY.odd);
return { id: data.id, label: typeof data.label === 'string' && data.label ? data.label : data.id, prompt_text: typeof data.prompt_text === 'string' ? data.prompt_text : '', prompt_text_source: data.prompt_text_source === 'asr' ? 'asr' : 'user' };
}
// A fresh synthesis every time. Only a real WAV comes back as playable; anything else is refused, never played.
export async function previewVoice(voice: string, text: string, signal: AbortSignal, f: Fetch = fetch): Promise<Blob> {
const r = await call(f, 'preview', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(text.trim() ? { voice, text: text.trim() } : { voice }), signal });
if (!r.ok) throw await refusal(r);
const data = await r.arrayBuffer().catch(() => null);
const info = data && wavInfo(data);
if (!data || !info || info.seconds <= 0) throw new VoiceError(SAY.badPreview);
return new Blob([data], { type: 'audio/wav' });
}
export async function applyVoice(voice: string, signal: AbortSignal, f: Fetch = fetch): Promise<VoiceSelection> {
const r = await call(f, 'selection', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ voice }), signal });
if (!r.ok) throw await refusal(r);
const s = selectionOf(await r.json().catch(() => null));
if (s.voice !== voice) throw new VoiceError(SAY.odd);
return s;
}
// ── Recording. Only ever started by a tap; stop, cancel, leaving or a lost track releases the microphone at once. ──
export type RecPhase = 'idle' | 'asking' | 'recording' | 'converting';
export interface RecView { phase: RecPhase; seconds: number }
export interface MediaParts {
getUserMedia(c: MediaStreamConstraints): Promise<MediaStream>;
recorder(stream: MediaStream): MediaRecorder;
secure(): boolean;
}
export const browserMedia: MediaParts = {
getUserMedia: c => navigator.mediaDevices.getUserMedia(c),
recorder: stream => new MediaRecorder(stream),
secure: () => typeof window !== 'undefined' && window.isSecureContext && !!navigator.mediaDevices?.getUserMedia,
};
function micFailure(e: unknown) {
const name = (e as { name?: string } | null)?.name || '';
if (name === 'NotFoundError' || name === 'DevicesNotFoundError' || name === 'OverconstrainedError') return SAY.noMic;
if (name === 'NotReadableError' || name === 'AbortError') return SAY.micBusy;
return SAY.denied;
}
export class Recorder {
private gen = 0;
private stream: MediaStream | null = null;
private rec: MediaRecorder | null = null;
private timer: ReturnType<typeof setInterval> | undefined;
private began = 0;
view: RecView = { phase: 'idle', seconds: 0 };
constructor(private on: { view(v: RecView): void; done(take: Blob): void; fail(message: string): void }, private media: MediaParts = browserMedia, private maxSeconds = SUGGEST_MAX, private now = () => Date.now()) {}
private show(v: RecView) { this.view = v; this.on.view(v); }
get busy() { return this.view.phase !== 'idle'; }
async start() {
if (this.busy) return;
const gen = ++this.gen;
if (!this.media.secure()) { this.on.fail(SAY.insecure); return; }
if (typeof MediaRecorder === 'undefined' && this.media === browserMedia) { this.on.fail(SAY.noRecorder); return; }
this.show({ phase: 'asking', seconds: 0 });
let stream: MediaStream;
// Audio only: no camera, and the browser's own echo/noise handling stays on.
try { stream = await this.media.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, video: false }); }
catch (e) { if (gen === this.gen) { this.show({ phase: 'idle', seconds: 0 }); this.on.fail(micFailure(e)); } return; }
// Cancelled (or left) while the permission prompt was up: the late microphone is closed, never used.
if (gen !== this.gen) { stream.getTracks().forEach(t => t.stop()); return; }
this.stream = stream;
let rec: MediaRecorder;
try { rec = this.media.recorder(stream); } catch { this.release(); this.show({ phase: 'idle', seconds: 0 }); this.on.fail(SAY.noRecorder); return; }
this.rec = rec;
const chunks: Blob[] = [];
rec.ondataavailable = e => { if (e.data?.size) chunks.push(e.data); };
rec.onstop = () => {
if (gen !== this.gen) return;
const take = new Blob(chunks, { type: rec.mimeType || chunks[0]?.type || '' });
this.release(); this.gen++;
this.show({ phase: 'converting', seconds: this.view.seconds });
this.on.done(take);
};
rec.onerror = () => { if (gen === this.gen) this.abandon(SAY.recordFailed); };
stream.getAudioTracks().forEach(t => t.addEventListener('ended', () => { if (gen === this.gen) this.abandon(SAY.micGone); }));
try { rec.start(250); } catch { this.abandon(SAY.recordFailed); return; }
this.began = this.now();
this.show({ phase: 'recording', seconds: 0 });
this.timer = setInterval(() => {
if (gen !== this.gen) return;
const seconds = (this.now() - this.began) / 1000;
if (seconds >= this.maxSeconds) { this.show({ phase: 'recording', seconds: this.maxSeconds }); this.stop(); return; }
this.show({ phase: 'recording', seconds });
}, 200);
}
// Keep what was recorded: the recorder flushes, then `done` hands the take over (and the microphone is already off).
stop() {
clearInterval(this.timer);
const rec = this.rec;
if (this.view.phase !== 'recording' || !rec || rec.state === 'inactive') { this.cancel(); return; }
this.view = { ...this.view, seconds: Math.min(this.maxSeconds, (this.now() - this.began) / 1000) };
try { rec.stop(); } catch { this.abandon(SAY.recordFailed); return; }
// The tracks stop now, not when the recorder gets round to its last chunk.
this.stream?.getTracks().forEach(t => t.stop());
}
// Throw the take away. Safe to call any time, also twice; a late permission answer is closed when it arrives.
cancel() { this.gen++; this.release(); if (this.view.phase !== 'idle') this.show({ phase: 'idle', seconds: 0 }); }
// The converted take was accepted or refused: back to idle.
settled() { if (this.view.phase === 'converting') this.show({ phase: 'idle', seconds: 0 }); }
private abandon(message: string) { this.cancel(); this.on.fail(message); }
private release() {
clearInterval(this.timer); this.timer = undefined;
const rec = this.rec; this.rec = null;
if (rec) { rec.ondataavailable = null; rec.onstop = null; rec.onerror = null; try { if (rec.state !== 'inactive') rec.stop(); } catch { /* Already stopped. */ } }
this.stream?.getTracks().forEach(t => t.stop()); this.stream = null;
}
}