dsh-voice 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * TTS 文本预处理、长文智能分段、MP3 帧拼接/静音生成、字幕格式化与试听卡片 HTML 渲染。
3
+ *
4
+ * @module dsh-voice/tts-text
5
+ */
6
+ import type { SubtitleCue } from './edge-tts.js';
7
+ /**
8
+ * 清洗 Markdown 为适合语音朗读的纯文本:
9
+ * 移除代码块、链接地址、裸 URL、标题/引用/强调标记与 HTML 标签,保留句末标点与段落结构。
10
+ */
11
+ export declare function cleanMarkdownForSpeech(text: string): string;
12
+ /**
13
+ * 按段落 → 句子 → 子句 → 空白 → 硬切分五级回退策略将长文本切分为不超过 maxChars 的非空段。
14
+ */
15
+ export declare function splitTextIntoChunks(text: string, maxChars?: number): string[];
16
+ /**
17
+ * 若 MP3 缓冲以 ID3v2 标签头开头,剥离其标签头(及可选 footer),避免多段拼接后在流中残留 ID3 头。
18
+ */
19
+ export declare function stripId3v2(mp3: Buffer): Buffer;
20
+ /**
21
+ * 生成合法的 MPEG-2 Layer III(24kHz 48kbps 单声道)静音 MP3 帧,每帧 144 字节 / 24ms。
22
+ */
23
+ export declare function createSilenceMp3(durationMs: number): Buffer;
24
+ /**
25
+ * 拼接多段 MP3:保留首段完整头部,后续段剥离 ID3v2 后拼接。
26
+ */
27
+ export declare function concatMp3Buffers(buffers: Buffer[]): Buffer;
28
+ /**
29
+ * 按 48kbps(6 字节/毫秒)估算 MP3 音频时长(毫秒)。
30
+ */
31
+ export declare function estimateMp3DurationMs(mp3: Buffer): number;
32
+ /**
33
+ * 平移字幕时间轴并从 startIndex 起重新编号。
34
+ */
35
+ export declare function offsetCues(cues: SubtitleCue[], offsetMs: number, startIndex?: number): SubtitleCue[];
36
+ /**
37
+ * 将字幕条目格式化为 SRT 或 WebVTT 文本。
38
+ */
39
+ export declare function formatSubtitles(cues: SubtitleCue[], format: 'srt' | 'vtt'): string;
40
+ /**
41
+ * 生成自包含、支持明暗主题与倍速播放的 HTML5 音色试听卡片页面。
42
+ */
43
+ export declare function renderPreviewHtml(samples: Array<{
44
+ voice: string;
45
+ fileName: string;
46
+ locale?: string;
47
+ gender?: string;
48
+ }>, text: string): string;
@@ -0,0 +1,308 @@
1
+ /**
2
+ * 清洗 Markdown 为适合语音朗读的纯文本:
3
+ * 移除代码块、链接地址、裸 URL、标题/引用/强调标记与 HTML 标签,保留句末标点与段落结构。
4
+ */
5
+ export function cleanMarkdownForSpeech(text) {
6
+ let out = text.replace(/\r\n?/g, '\n');
7
+ // 移除围栏代码块(``` 与 ~~~)
8
+ out = out.replace(/```[\s\S]*?```/g, '');
9
+ out = out.replace(/~~~[\s\S]*?~~~/g, '');
10
+ // 行内代码保留内容,仅去反引号
11
+ out = out.replace(/`([^`]+)`/g, '$1');
12
+ // 图片与链接保留可读文本
13
+ out = out.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1');
14
+ out = out.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
15
+ // 裸 URL
16
+ out = out.replace(/https?:\/\/\S+/g, '');
17
+ // HTML 标签
18
+ out = out.replace(/<[^>]+>/g, '');
19
+ // 标题、引用、水平分割线、无序列表符号
20
+ out = out.replace(/^#{1,6}\s+/gm, '');
21
+ out = out.replace(/^>\s*/gm, '');
22
+ out = out.replace(/^\s*(?:[-*_]\s*){3,}$/gm, '');
23
+ out = out.replace(/^\s*[-*+]\s+/gm, '');
24
+ // 粗体、斜体、删除线标记
25
+ out = out.replace(/(\*\*|__|~~|\*)/g, '');
26
+ // 折叠行内多余空白并规范段落空行
27
+ out = out.replace(/[ \t]+/g, ' ');
28
+ out = out.replace(/^[ \t]+|[ \t]+$/gm, '');
29
+ out = out.replace(/\n{3,}/g, '\n\n');
30
+ return out.trim();
31
+ }
32
+ function needsSpaceBetween(left, right) {
33
+ return /[A-Za-z0-9.?!;,:]$/.test(left) && /^[A-Za-z0-9]/.test(right);
34
+ }
35
+ function splitAtLevel(unit, maxChars, level) {
36
+ const trimmed = unit.trim();
37
+ if (trimmed === '')
38
+ return [];
39
+ if (trimmed.length <= maxChars)
40
+ return [trimmed];
41
+ if (level >= 4) {
42
+ const slices = [];
43
+ for (let i = 0; i < trimmed.length; i += maxChars) {
44
+ const part = trimmed.slice(i, i + maxChars).trim();
45
+ if (part !== '')
46
+ slices.push(part);
47
+ }
48
+ return slices;
49
+ }
50
+ const splitters = [
51
+ /\n+/,
52
+ /(?<=[。!?;.!?;])\s*/,
53
+ /(?<=[,、,::])\s*/,
54
+ /\s+/,
55
+ ];
56
+ const rawParts = trimmed
57
+ .split(splitters[level])
58
+ .map((part) => part.trim())
59
+ .filter((part) => part !== '');
60
+ if (rawParts.length <= 1) {
61
+ return splitAtLevel(trimmed, maxChars, level + 1);
62
+ }
63
+ const chunks = [];
64
+ let current = '';
65
+ for (const part of rawParts) {
66
+ if (part.length > maxChars) {
67
+ if (current !== '') {
68
+ chunks.push(current);
69
+ current = '';
70
+ }
71
+ chunks.push(...splitAtLevel(part, maxChars, level + 1));
72
+ continue;
73
+ }
74
+ if (current === '') {
75
+ current = part;
76
+ continue;
77
+ }
78
+ const sep = level === 0 ? '\n\n' : level === 3 ? ' ' : (needsSpaceBetween(current, part) ? ' ' : '');
79
+ if (current.length + sep.length + part.length <= maxChars) {
80
+ current += sep + part;
81
+ }
82
+ else {
83
+ chunks.push(current);
84
+ current = part;
85
+ }
86
+ }
87
+ if (current !== '')
88
+ chunks.push(current);
89
+ return chunks;
90
+ }
91
+ /**
92
+ * 按段落 → 句子 → 子句 → 空白 → 硬切分五级回退策略将长文本切分为不超过 maxChars 的非空段。
93
+ */
94
+ export function splitTextIntoChunks(text, maxChars = 2800) {
95
+ const trimmed = text.trim();
96
+ if (trimmed === '')
97
+ return [];
98
+ const limit = Math.max(1, Math.floor(maxChars));
99
+ if (trimmed.length <= limit)
100
+ return [trimmed];
101
+ return splitAtLevel(trimmed, limit, 0);
102
+ }
103
+ /**
104
+ * 若 MP3 缓冲以 ID3v2 标签头开头,剥离其标签头(及可选 footer),避免多段拼接后在流中残留 ID3 头。
105
+ */
106
+ export function stripId3v2(mp3) {
107
+ if (mp3.length < 10)
108
+ return mp3;
109
+ if (mp3[0] !== 0x49 || mp3[1] !== 0x44 || mp3[2] !== 0x33)
110
+ return mp3; // 'ID3'
111
+ if (mp3[3] === 0xff || mp3[4] === 0xff)
112
+ return mp3;
113
+ if ((mp3[6] & 0x80) !== 0 || (mp3[7] & 0x80) !== 0 || (mp3[8] & 0x80) !== 0 || (mp3[9] & 0x80) !== 0) {
114
+ return mp3;
115
+ }
116
+ const tagSize = ((mp3[6] & 0x7f) << 21)
117
+ | ((mp3[7] & 0x7f) << 14)
118
+ | ((mp3[8] & 0x7f) << 7)
119
+ | (mp3[9] & 0x7f);
120
+ const footerSize = (mp3[5] & 0x10) !== 0 ? 10 : 0;
121
+ const totalHeader = 10 + tagSize + footerSize;
122
+ if (mp3.length < totalHeader)
123
+ return mp3;
124
+ return mp3.subarray(totalHeader);
125
+ }
126
+ /**
127
+ * 生成合法的 MPEG-2 Layer III(24kHz 48kbps 单声道)静音 MP3 帧,每帧 144 字节 / 24ms。
128
+ */
129
+ export function createSilenceMp3(durationMs) {
130
+ if (!Number.isFinite(durationMs) || durationMs <= 0)
131
+ return Buffer.alloc(0);
132
+ const frames = Math.max(1, Math.round(durationMs / 24));
133
+ const frameSize = 144;
134
+ const out = Buffer.alloc(frames * frameSize);
135
+ for (let i = 0; i < frames; i++) {
136
+ const offset = i * frameSize;
137
+ out[offset] = 0xff;
138
+ out[offset + 1] = 0xf3;
139
+ out[offset + 2] = 0x64;
140
+ out[offset + 3] = 0xc0;
141
+ }
142
+ return out;
143
+ }
144
+ /**
145
+ * 拼接多段 MP3:保留首段完整头部,后续段剥离 ID3v2 后拼接。
146
+ */
147
+ export function concatMp3Buffers(buffers) {
148
+ const nonEmpty = buffers.filter((buf) => buf.length > 0);
149
+ if (nonEmpty.length === 0)
150
+ return Buffer.alloc(0);
151
+ const normalized = nonEmpty.map((buf, index) => (index === 0 ? buf : stripId3v2(buf)));
152
+ return Buffer.concat(normalized);
153
+ }
154
+ /**
155
+ * 按 48kbps(6 字节/毫秒)估算 MP3 音频时长(毫秒)。
156
+ */
157
+ export function estimateMp3DurationMs(mp3) {
158
+ return Math.round((stripId3v2(mp3).length * 8) / 48);
159
+ }
160
+ /**
161
+ * 平移字幕时间轴并从 startIndex 起重新编号。
162
+ */
163
+ export function offsetCues(cues, offsetMs, startIndex = 1) {
164
+ return cues.map((cue, idx) => ({
165
+ index: startIndex + idx,
166
+ startMs: cue.startMs + offsetMs,
167
+ endMs: cue.endMs + offsetMs,
168
+ text: cue.text,
169
+ }));
170
+ }
171
+ function formatSubtitleTimestamp(ms, decimalSep) {
172
+ const safe = Math.max(0, Math.round(ms));
173
+ const hours = Math.floor(safe / 3600000);
174
+ const minutes = Math.floor((safe % 3600000) / 60000);
175
+ const seconds = Math.floor((safe % 60000) / 1000);
176
+ const millis = safe % 1000;
177
+ return String(hours).padStart(2, '0')
178
+ + ':' + String(minutes).padStart(2, '0')
179
+ + ':' + String(seconds).padStart(2, '0')
180
+ + decimalSep + String(millis).padStart(3, '0');
181
+ }
182
+ /**
183
+ * 将字幕条目格式化为 SRT 或 WebVTT 文本。
184
+ */
185
+ export function formatSubtitles(cues, format) {
186
+ if (format === 'vtt') {
187
+ if (cues.length === 0)
188
+ return 'WEBVTT\n\n';
189
+ const blocks = cues.map((cue) => formatSubtitleTimestamp(cue.startMs, '.')
190
+ + ' --> '
191
+ + formatSubtitleTimestamp(cue.endMs, '.')
192
+ + '\n'
193
+ + cue.text);
194
+ return 'WEBVTT\n\n' + blocks.join('\n\n') + '\n';
195
+ }
196
+ if (cues.length === 0)
197
+ return '';
198
+ return cues
199
+ .map((cue, idx) => String(idx + 1)
200
+ + '\n'
201
+ + formatSubtitleTimestamp(cue.startMs, ',')
202
+ + ' --> '
203
+ + formatSubtitleTimestamp(cue.endMs, ',')
204
+ + '\n'
205
+ + cue.text)
206
+ .join('\n\n') + '\n';
207
+ }
208
+ function escapeHtml(value) {
209
+ return value
210
+ .replace(/&/g, '&amp;')
211
+ .replace(/</g, '&lt;')
212
+ .replace(/>/g, '&gt;')
213
+ .replace(/"/g, '&quot;')
214
+ .replace(/'/g, '&#39;');
215
+ }
216
+ /**
217
+ * 生成自包含、支持明暗主题与倍速播放的 HTML5 音色试听卡片页面。
218
+ */
219
+ export function renderPreviewHtml(samples, text) {
220
+ const cards = samples.map((sample) => {
221
+ const safeVoice = escapeHtml(sample.voice);
222
+ const safeFile = escapeHtml(sample.fileName);
223
+ const metaParts = [sample.locale, sample.gender].filter((item) => typeof item === 'string' && item !== '');
224
+ const metaHtml = metaParts.length > 0
225
+ ? '<p class="meta">' + metaParts.map((item) => escapeHtml(item)).join(' · ') + '</p>'
226
+ : '';
227
+ return [
228
+ ' <article class="card">',
229
+ ' <div class="card-head">',
230
+ ' <div>',
231
+ ' <h2>' + safeVoice + '</h2>',
232
+ metaHtml,
233
+ ' </div>',
234
+ ' <button type="button" class="copy-btn" data-voice="' + safeVoice + '">复制 ID</button>',
235
+ ' </div>',
236
+ ' <audio controls preload="none" src="./' + safeFile + '"></audio>',
237
+ ' </article>',
238
+ ].filter(Boolean).join('\n');
239
+ }).join('\n');
240
+ return [
241
+ '<!DOCTYPE html>',
242
+ '<html lang="zh-CN">',
243
+ '<head>',
244
+ ' <meta charset="UTF-8">',
245
+ ' <meta name="viewport" content="width=device-width, initial-scale=1.0">',
246
+ ' <title>dsh-voice 音色试听对比</title>',
247
+ ' <style>',
248
+ ' :root { color-scheme: light dark; --bg: #f6f7f9; --card: #ffffff; --fg: #181a1f; --muted: #5c6370; --border: #e1e4e8; --accent: #2563eb; }',
249
+ ' @media (prefers-color-scheme: dark) { :root { --bg: #0f1117; --card: #181b24; --fg: #eceef2; --muted: #9aa2b1; --border: #2a2f3d; --accent: #60a5fa; } }',
250
+ ' * { box-sizing: border-box; }',
251
+ ' body { margin: 0; padding: 24px; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--fg); }',
252
+ ' .wrap { max-width: 920px; margin: 0 auto; }',
253
+ ' header { display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; align-items: center; margin-bottom: 16px; }',
254
+ ' h1 { margin: 0; font-size: 1.35rem; }',
255
+ ' .quote { margin: 0 0 20px; padding: 12px 14px; background: var(--card); border: 1px solid var(--border); border-radius: 10px; color: var(--muted); line-height: 1.5; }',
256
+ ' .controls { display: flex; align-items: center; gap: 8px; font-size: 0.9rem; }',
257
+ ' select, .copy-btn { padding: 6px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--card); color: var(--fg); cursor: pointer; }',
258
+ ' .copy-btn:hover { border-color: var(--accent); color: var(--accent); }',
259
+ ' .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 14px; }',
260
+ ' .card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 14px; display: flex; flex-direction: column; gap: 10px; }',
261
+ ' .card-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 8px; }',
262
+ ' h2 { margin: 0; font-size: 1rem; word-break: break-all; }',
263
+ ' .meta { margin: 4px 0 0; font-size: 0.85rem; color: var(--muted); }',
264
+ ' audio { width: 100%; }',
265
+ ' </style>',
266
+ '</head>',
267
+ '<body>',
268
+ ' <main class="wrap">',
269
+ ' <header>',
270
+ ' <h1>音色试听对比</h1>',
271
+ ' <label class="controls">倍速播放:',
272
+ ' <select id="rate-select">',
273
+ ' <option value="0.8">0.8x</option>',
274
+ ' <option value="1.0" selected>1.0x</option>',
275
+ ' <option value="1.2">1.2x</option>',
276
+ ' <option value="1.5">1.5x</option>',
277
+ ' </select>',
278
+ ' </label>',
279
+ ' </header>',
280
+ ' <p class="quote">试听文本:' + escapeHtml(text) + '</p>',
281
+ ' <section class="grid">',
282
+ cards,
283
+ ' </section>',
284
+ ' </main>',
285
+ ' <script>',
286
+ ' const rateSelect = document.getElementById("rate-select");',
287
+ ' rateSelect.addEventListener("change", () => {',
288
+ ' const rate = Number(rateSelect.value) || 1;',
289
+ ' for (const el of document.querySelectorAll("audio")) el.playbackRate = rate;',
290
+ ' });',
291
+ ' for (const btn of document.querySelectorAll(".copy-btn")) {',
292
+ ' btn.addEventListener("click", async () => {',
293
+ ' const id = btn.getAttribute("data-voice") || "";',
294
+ ' try {',
295
+ ' await navigator.clipboard.writeText(id);',
296
+ ' const prev = btn.textContent;',
297
+ ' btn.textContent = "已复制";',
298
+ ' setTimeout(() => { btn.textContent = prev; }, 1200);',
299
+ ' } catch {',
300
+ ' window.prompt("复制音色 ID:", id);',
301
+ ' }',
302
+ ' });',
303
+ ' }',
304
+ ' </script>',
305
+ '</body>',
306
+ '</html>',
307
+ ].join('\n') + '\n';
308
+ }