Add browser Piper Chinese voices and fix timeline scale (#2)

Co-authored-by: haixin.yang <haixin.yang@weimob.com>
This commit is contained in:
MartinDelophyandhaixin.yang authored and GitHub committed 2026-07-15 10:09:58 +08:00
1 parent 3586ec8aab
commit 46ec49bd52
9 files changed
+193 -13

No files matched your search

+7
View File
@@ -18,6 +18,7 @@
"fflate": "^0.8.3",
"kokoro-js": "^1.2.1",
"onnxruntime-web": "^1.27.0",
"pinyin-pro": "^3.27.0",
"react": "19.2.0",
"react-dom": "19.2.0"
},
@@ -4025,6 +4026,12 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/pinyin-pro": {
"version": "3.27.0",
"resolved": "https://registry.npmmirror.com/pinyin-pro/-/pinyin-pro-3.27.0.tgz",
"integrity": "sha512-Osdgjwe7Rm17N2paDMM47yW+jUIUH3+0RGo8QP39ZTLpTaJVDK0T58hOLaMQJbcMmAebVuK2ePunTEVEx1clNQ==",
"license": "MIT"
},
"node_modules/platform": {
"version": "1.3.6",
"resolved": "https://registry.npmmirror.com/platform/-/platform-1.3.6.tgz",
+1
View File
@@ -36,6 +36,7 @@
"fflate": "^0.8.3",
"kokoro-js": "^1.2.1",
"onnxruntime-web": "^1.27.0",
"pinyin-pro": "^3.27.0",
"react": "19.2.0",
"react-dom": "19.2.0"
},
+8 -8
View File
@@ -69,22 +69,22 @@ export const AUDIO_RECORDING_FORMATS = [
export const VOICES = [
{
id: "zh_CN-huayan-medium",
name: "华言",
id: "zh_CN-xiao_ya-medium",
name: "小雅",
language: "中文",
detail: "Piper ONNX · 普通话",
gender: "温柔女声",
gender: "自然女声",
engine: "piper",
badge: "推荐",
},
{
id: "zh_CN-huayan-x_low",
name: "轻量华言",
id: "zh_CN-chaowen-medium",
name: "超文",
language: "中文",
detail: "Piper ONNX · 小模型",
gender: "快速预览",
detail: "Piper ONNX · 普通话",
gender: "自然人声",
engine: "piper",
badge: "轻量",
badge: "ONNX",
},
{
id: "af_heart",
+1 -1
View File
@@ -22,7 +22,7 @@ export function useAudioTrackState() {
const [sourceAudioPeaks, setSourceAudioPeaks] = useState([]);
const [sourceAudioVolume, setSourceAudioVolume] = useState(1);
const [sourceAudioStart, setSourceAudioStart] = useState(0);
const [favoriteVoiceIds, setFavoriteVoiceIds] = useState(["zh_CN-huayan-medium"]);
const [favoriteVoiceIds, setFavoriteVoiceIds] = useState(["zh_CN-xiao_ya-medium"]);
const [historyItems, setHistoryItems] = useState([]);
const [recordedVoices, setRecordedVoices] = useState([]);
const [recordingState, setRecordingState] = useState("idle");
+3 -2
View File
@@ -1,5 +1,6 @@
import { useCallback } from "react";
import { MODEL_ID } from "../config/editor.js";
import { predictPiperVoice } from "../lib/piperVoiceRuntime.js";
import { clearPiperCacheIfStorageTight, isPiperSymbolError, isStorageQuotaError, prepareTextForVoice, TtsInputError } from "../lib/ttsText.js";
export function useVoiceGeneration(d) {
@@ -22,10 +23,10 @@ export function useVoiceGeneration(d) {
d.setStatusText(d.t("ttsStatusLoadingChineseModel"));
const progress = (event) => { if (event?.total) d.setProgress((current) => Math.max(current, Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))))); };
const input = { text: prepared.text, voiceId: d.selectedVoice.id };
try { blob = await tts.predict(input, progress); }
try { blob = await predictPiperVoice(tts, input, progress); }
catch (error) {
if (!isStorageQuotaError(error)) throw error;
d.setStatusText(d.t("ttsStatusClearingCache")); await tts.flush?.(); blob = await tts.predict(input, progress);
d.setStatusText(d.t("ttsStatusClearingCache")); await tts.flush?.(); blob = await predictPiperVoice(tts, input, progress);
}
} else {
const { KokoroTTS } = await import("kokoro-js"); d.setStatusText(d.t("ttsStatusLoadingKokoro"));
+135
View File
@@ -0,0 +1,135 @@
import * as ort from "onnxruntime-web/webgpu";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
import { pinyin } from "pinyin-pro";
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
const PINYIN_VOICES = {
"zh_CN-xiao_ya-medium": "zh/zh_CN/xiao_ya/medium",
"zh_CN-chaowen-medium": "zh/zh_CN/chaowen/medium",
};
const PIPER_BASE = "https://huggingface.co/rhasspy/piper-voices/resolve/main";
const INITIALS = ["zh", "ch", "sh", "b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "r", "z", "c", "s", "y", "w"];
const GROUP_END = new Set(["1", "2", "3", "4", "5", "。", ".", "?", "?", "!", "!", "—", "…", "、", ",", ",", ":", ":", ";", ";", " "]);
const DIGITS = { 0: "零", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九" };
const pinyinRuntimePromises = new Map();
function normalizeNumbers(text) {
return text.replace(/\d/g, (digit) => DIGITS[digit]);
}
function splitSyllable(syllable) {
const match = /^([a-züv:]+)([1-5])$/i.exec(syllable);
if (!match) return null;
let base = match[1].toLowerCase().replaceAll("u:", "v").replaceAll("ü", "v");
const initial = INITIALS.find((candidate) => base.startsWith(candidate)) ?? "Ø";
let final = initial === "Ø" ? base : base.slice(initial.length);
if (["j", "q", "x"].includes(initial)) {
if (final === "u") final = "v";
else if (final === "ue") final = "ve";
else if (final === "uan") final = "van";
else if (final === "un") final = "vn";
}
return [initial, final, match[2]];
}
export function phonemizeXiaoYa(text, phonemeIdMap) {
const symbols = [];
for (const token of pinyin(normalizeNumbers(text), { toneType: "num", type: "array" })) {
const syllable = splitSyllable(token);
if (syllable) symbols.push(...syllable);
else if (token in phonemeIdMap) symbols.push(token);
}
const ids = [...phonemeIdMap["^"]];
for (const symbol of symbols) {
const symbolIds = phonemeIdMap[symbol];
if (!symbolIds) throw new Error(`小雅不支持音素:${symbol}`);
ids.push(...symbolIds);
if (GROUP_END.has(symbol)) ids.push(...phonemeIdMap._);
}
ids.push(...phonemeIdMap.$);
return ids;
}
function encodeWav(samples, sampleRate) {
const buffer = new ArrayBuffer(44 + samples.length * 2);
const view = new DataView(buffer);
const write = (offset, value) => [...value].forEach((char, index) => view.setUint8(offset + index, char.charCodeAt(0)));
write(0, "RIFF"); view.setUint32(4, buffer.byteLength - 8, true); write(8, "WAVE"); write(12, "fmt ");
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
write(36, "data"); view.setUint32(40, samples.length * 2, true);
samples.forEach((sample, index) => view.setInt16(44 + index * 2, Math.max(-1, Math.min(1, sample)) * 32767, true));
return new Blob([buffer], { type: "audio/wav" });
}
async function fetchArrayBufferWithProgress(url, onProgress, voiceName) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${voiceName}模型下载失败 (${response.status})`);
const total = Number(response.headers.get("content-length")) || 0;
if (!response.body) return response.arrayBuffer();
const reader = response.body.getReader();
const chunks = [];
let loaded = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value); loaded += value.byteLength;
onProgress?.({ url, total, loaded });
}
const bytes = new Uint8Array(loaded);
let offset = 0;
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
return bytes.buffer;
}
async function loadPinyinVoice(voiceId, onProgress) {
const voicePath = PINYIN_VOICES[voiceId];
const voiceName = voiceId === "zh_CN-xiao_ya-medium" ? "小雅" : "超文";
const voiceBase = `${PIPER_BASE}/${voicePath}`;
const configResponse = await fetch(`${voiceBase}/${voiceId}.onnx.json`);
if (!configResponse.ok) throw new Error(`${voiceName}配置下载失败 (${configResponse.status})`);
const config = await configResponse.json();
const model = await fetchArrayBufferWithProgress(`${voiceBase}/${voiceId}.onnx`, onProgress, voiceName);
const session = await ort.InferenceSession.create(model, { executionProviders: ["wasm"] });
return { config, session };
}
async function predictPinyinVoice(input, onProgress) {
if (!pinyinRuntimePromises.has(input.voiceId)) {
pinyinRuntimePromises.set(
input.voiceId,
loadPinyinVoice(input.voiceId, onProgress).catch((error) => {
pinyinRuntimePromises.delete(input.voiceId);
throw error;
}),
);
}
const { config, session } = await pinyinRuntimePromises.get(input.voiceId);
const ids = phonemizeXiaoYa(input.text.trim(), config.phoneme_id_map);
const feeds = {
input: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, ids.length]),
input_lengths: new ort.Tensor("int64", BigInt64Array.from([ids.length], BigInt), [1]),
scales: new ort.Tensor("float32", Float32Array.from([
config.inference.noise_scale,
config.inference.length_scale,
config.inference.noise_w,
]), [3]),
};
const result = await session.run(feeds);
const samples = result.output.data;
if (!(samples instanceof Float32Array) || !samples.length || samples.some((sample) => !Number.isFinite(sample))) {
throw new Error("小雅生成了无效音频");
}
return encodeWav(samples, config.audio.sample_rate);
}
export async function predictPiperVoice(tts, input, onProgress) {
if (input.voiceId in PINYIN_VOICES) return predictPinyinVoice(input, onProgress);
return tts.predict(input, onProgress);
}
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it, vi } from "vitest";
import { phonemizeXiaoYa, predictPiperVoice } from "./piperVoiceRuntime.js";
describe("Piper voice runtime", () => {
it("converts Mandarin syllables into Xiao Ya initial/final/tone groups", () => {
const map = {
_: [0], "^": [1], $: [2], n: [10], i: [39], 3: [66], h: [14], ao: [32],
",": [72], zh: [18], e: [29], 4: [67], sh: [20], 5: [68], x: [17], iao: [42], y: [25], a: [27], "。": [69],
};
const ids = phonemizeXiaoYa("你好,这是小雅。", map);
expect(ids).toEqual([
1, 10, 39, 66, 0, 14, 32, 66, 0, 72, 0, 18, 29, 67, 0, 20, 39, 67, 0,
17, 42, 66, 0, 25, 27, 66, 0, 69, 0, 2,
]);
});
it("keeps unknown legacy voices on the bundled Piper runtime", async () => {
const tts = { predict: vi.fn(async () => new Blob(["wav"])) };
await predictPiperVoice(tts, { text: "你好", voiceId: "legacy-voice" });
expect(tts.predict).toHaveBeenCalledOnce();
});
});
+1 -1
View File
@@ -179,7 +179,7 @@ export async function clearPiperCacheIfStorageTight(tts) {
const usage = estimate.usage ?? 0;
const quota = estimate.quota ?? 0;
const remaining = quota > usage ? quota - usage : 0;
if (quota > 0 && (usage / quota > 0.9 || remaining < 120 * 1024 * 1024)) {
if (quota > 0 && (usage / quota > 0.85 || remaining < 200 * 1024 * 1024)) {
await tts.flush();
return true;
}
+14 -1
View File
@@ -3795,9 +3795,16 @@ button:disabled {
.audio-clip {
position: relative;
min-width: 72px;
min-width: 0;
max-width: 100%;
height: 44px;
container-type: inline-size;
}
.audio-clip::before {
position: absolute;
inset: -4px -5px;
content: "";
}
.audio-track:not(.source-track):not(.music-track) .audio-clip {
@@ -4036,6 +4043,12 @@ button:disabled {
background: rgba(0, 0, 0, 0.7);
}
@container (max-width: 68px) {
.audio-clip-duration {
display: none;
}
}
.waveform-strip.is-active span {
opacity: 0.95;
background: #34ead8;