soma-voice 2.0.0 → 3.0.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.
- package/README.md +153 -54
- package/manifest.md +7 -8
- package/package.json +9 -12
- package/src/api/service/index.ts +0 -2
- package/src/api/service/voice/Synthesize.ts +3 -2
- package/src/api/service/voice/Transcribe.ts +5 -5
- package/src/client/browser-voice.ts +337 -0
- package/src/client/capabilities.ts +272 -50
- package/src/client/errors.ts +23 -5
- package/src/client/http.ts +164 -147
- package/src/client/index.ts +3 -9
- package/src/client/player.ts +386 -82
- package/src/client/recorder.ts +616 -209
- package/src/client/wav.ts +28 -0
- package/src/server/concurrency.ts +38 -20
- package/src/server/config.ts +122 -71
- package/src/server/errors.ts +14 -1
- package/src/server/index.ts +0 -4
- package/src/server/runtime.ts +301 -241
- package/src/shared/audio-format.ts +86 -0
- package/src/shared/transcription.ts +92 -0
- package/src/api/service/voice/synthesize/Stream.ts +0 -15
- package/src/api/service/voice/transcribe/Raw.ts +0 -15
- package/src/client/audio-conversion.ts +0 -127
- package/src/client/audio-processing.ts +0 -153
- package/src/client/browser-codec.ts +0 -73
- package/src/client/indexeddb-storage.ts +0 -109
- package/src/client/offline.ts +0 -139
- package/src/client/realtime-stt.ts +0 -261
- package/src/client/storage.ts +0 -89
- package/src/client/streaming-tts.ts +0 -156
- package/src/client/transports.ts +0 -221
- package/src/server/raw-transcription.ts +0 -70
- package/src/server/speech-stream.ts +0 -176
- package/src/server/streaming.ts +0 -160
- package/src/server/upload.ts +0 -94
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveSpeechEnvironment,
|
|
3
|
+
type VoiceEnvironment,
|
|
4
|
+
type VoiceSpeechSynthesis,
|
|
5
|
+
} from './capabilities';
|
|
6
|
+
import { VoiceError } from './errors';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 朗读来源:
|
|
10
|
+
* - `'server'`(默认):Host 后端合成,各设备音色一致;
|
|
11
|
+
* - `'browser-first'`:先用浏览器的本地系统音色,没有合适音色或起播失败时自动降级到后端。
|
|
12
|
+
* 识别不在此列,始终走后端。
|
|
13
|
+
*/
|
|
14
|
+
export type SpeechVoiceSource = 'server' | 'browser-first';
|
|
15
|
+
|
|
16
|
+
/** `'spoken'`:已完整读完;`'unavailable'`:没能起播,调用方应降级到后端。 */
|
|
17
|
+
export type BrowserSpeechOutcome = 'spoken' | 'unavailable';
|
|
18
|
+
|
|
19
|
+
export interface FindLocalBrowserVoiceOptions {
|
|
20
|
+
environment?: VoiceEnvironment;
|
|
21
|
+
/** getVoices() 为空时等待 voiceschanged 的上限,默认 1000ms;0 表示不等。 */
|
|
22
|
+
waitMs?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SpeakWithBrowserVoiceOptions {
|
|
26
|
+
voice: SpeechSynthesisVoice;
|
|
27
|
+
/** BCP-47 语言标签;与 voice 一并设在 utterance 上(部分 Android 浏览器按 lang 而非 voice 选音色)。 */
|
|
28
|
+
lang: string;
|
|
29
|
+
/** 语速,夹在 0.5–2;缺省 1。 */
|
|
30
|
+
rate?: number;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
environment?: VoiceEnvironment;
|
|
33
|
+
/** 起播看门狗:speak() 后这么久仍没有 start 事件就判为不可用,默认 2000ms。 */
|
|
34
|
+
startTimeoutMs?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const VOICES_WAIT_MS = 1_000;
|
|
38
|
+
const START_TIMEOUT_MS = 2_000;
|
|
39
|
+
/** setTimeout 延迟的上限(2^31-1 ms)。 */
|
|
40
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
41
|
+
const MIN_RATE = 0.5;
|
|
42
|
+
const MAX_RATE = 2;
|
|
43
|
+
|
|
44
|
+
interface OwnSpeech {
|
|
45
|
+
synthesis: VoiceSpeechSynthesis;
|
|
46
|
+
/** 以 ABORTED 收尾这次调用、不 cancel():它已被更新的朗读或后端播放取代。 */
|
|
47
|
+
supersede(): void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 本模块发起、仍在进行的朗读:utterance → 所在的 synthesis 与收尾函数。
|
|
52
|
+
* 兼作引用持有:Chrome 已知问题,utterance 若只被引擎队列持有、JS 侧再无引用,可能被垃圾回收,
|
|
53
|
+
* end / error 事件随之丢失,Promise 永远挂起。朗读期间在这里持有引用,收尾时释放。
|
|
54
|
+
*/
|
|
55
|
+
const ownSpeech = new Map<SpeechSynthesisUtterance, OwnSpeech>();
|
|
56
|
+
|
|
57
|
+
function normalizeLang(tag: unknown): string {
|
|
58
|
+
// Android 旧版报告 `zh_CN` 这类下划线写法。
|
|
59
|
+
return typeof tag === 'string' ? tag.trim().replace(/_/g, '-').toLowerCase() : '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 主子标签一档的比对键。zh 之下普通话与粤语是两种口语:zh-HK / zh-MO 的本地音色是粤语
|
|
64
|
+
* (iOS Sinji、Windows「Microsoft Tracy (Hong Kong)」、Android 粤语引擎),拿它读普通话文本等于换了语言。
|
|
65
|
+
* 所以带 HK / MO 地区或 yue 子标签的 zh,与主子标签 yue 一起归为 `yue`,只和粤语请求互相匹配。
|
|
66
|
+
*/
|
|
67
|
+
function spokenLanguage(tag: string): string {
|
|
68
|
+
const [primary = '', ...rest] = tag.split('-');
|
|
69
|
+
if (primary === 'zh' && rest.some((subtag) => subtag === 'hk' || subtag === 'mo' || subtag === 'yue')) {
|
|
70
|
+
return 'yue';
|
|
71
|
+
}
|
|
72
|
+
return primary;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function delayOr(value: number | undefined, fallback: number, allowZero: boolean): number {
|
|
76
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;
|
|
77
|
+
if (value < 0 || (!allowZero && value === 0)) return fallback;
|
|
78
|
+
return Math.min(value, MAX_TIMEOUT_MS);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function clampRate(rate: number | undefined): number {
|
|
82
|
+
if (typeof rate !== 'number' || !Number.isFinite(rate)) return 1;
|
|
83
|
+
return Math.min(MAX_RATE, Math.max(MIN_RATE, rate));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function readVoices(synthesis: VoiceSpeechSynthesis): SpeechSynthesisVoice[] {
|
|
87
|
+
try {
|
|
88
|
+
const voices = synthesis.getVoices();
|
|
89
|
+
return voices ? Array.from(voices) : [];
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Chrome 的 getVoices() 首次调用常返回空数组,音色列表异步加载完才触发 voiceschanged。
|
|
97
|
+
* voiceschanged 可能不止一次(首次仍为空):列表非空才收尾,否则等到超时,由调用方再读一次。
|
|
98
|
+
*/
|
|
99
|
+
function waitForVoices(synthesis: VoiceSpeechSynthesis, waitMs: number): Promise<void> {
|
|
100
|
+
return new Promise<void>((resolve) => {
|
|
101
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
102
|
+
const done = () => {
|
|
103
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
104
|
+
timer = undefined;
|
|
105
|
+
try {
|
|
106
|
+
synthesis.removeEventListener?.('voiceschanged', onChange);
|
|
107
|
+
} catch {
|
|
108
|
+
// 忽略:没有事件接口的实现只靠超时。
|
|
109
|
+
}
|
|
110
|
+
resolve();
|
|
111
|
+
};
|
|
112
|
+
const onChange = () => {
|
|
113
|
+
if (readVoices(synthesis).length) done();
|
|
114
|
+
};
|
|
115
|
+
try {
|
|
116
|
+
synthesis.addEventListener?.('voiceschanged', onChange);
|
|
117
|
+
} catch {
|
|
118
|
+
// 同上。
|
|
119
|
+
}
|
|
120
|
+
timer = setTimeout(done, waitMs);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 同等匹配(精确 > 主子标签,粤语与普通话互不匹配)中优先 voice.default,再按列表顺序。 */
|
|
125
|
+
function pickLocalVoice(
|
|
126
|
+
voices: readonly SpeechSynthesisVoice[],
|
|
127
|
+
wanted: string,
|
|
128
|
+
): SpeechSynthesisVoice | undefined {
|
|
129
|
+
const language = spokenLanguage(wanted);
|
|
130
|
+
let best: SpeechSynthesisVoice | undefined;
|
|
131
|
+
let bestScore = 0;
|
|
132
|
+
for (const voice of voices) {
|
|
133
|
+
// 只收本地音色:Chrome 的 Google 在线音色(localService=false)会把文本发往云端,
|
|
134
|
+
// 长文本约 15 秒即被截断,不作为「浏览器本地朗读」使用。
|
|
135
|
+
if (!voice || voice.localService !== true) continue;
|
|
136
|
+
const tag = normalizeLang(voice.lang);
|
|
137
|
+
if (!tag) continue;
|
|
138
|
+
const match = tag === wanted ? 2 : spokenLanguage(tag) === language ? 1 : 0;
|
|
139
|
+
if (!match) continue;
|
|
140
|
+
const score = match * 2 + (voice.default ? 1 : 0);
|
|
141
|
+
if (score > bestScore) {
|
|
142
|
+
best = voice;
|
|
143
|
+
bestScore = score;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return best;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 找一个匹配 lang 的浏览器本地音色:先精确匹配(`zh-CN`),再匹配主子标签(`zh`);
|
|
151
|
+
* 粤语(`zh-HK`、`zh-MO`、`yue`)与普通话在主子标签一档互不匹配。
|
|
152
|
+
* 没有朗读 API、音色列表为空或只有在线音色时返回 undefined。
|
|
153
|
+
*/
|
|
154
|
+
export async function findLocalBrowserVoice(
|
|
155
|
+
lang: string,
|
|
156
|
+
options: FindLocalBrowserVoiceOptions = {},
|
|
157
|
+
): Promise<SpeechSynthesisVoice | undefined> {
|
|
158
|
+
const wanted = normalizeLang(lang);
|
|
159
|
+
if (!wanted) return undefined;
|
|
160
|
+
const synthesis = resolveSpeechEnvironment(options.environment).speechSynthesis;
|
|
161
|
+
if (!synthesis || typeof synthesis.getVoices !== 'function') return undefined;
|
|
162
|
+
let voices = readVoices(synthesis);
|
|
163
|
+
if (!voices.length) {
|
|
164
|
+
const waitMs = delayOr(options.waitMs, VOICES_WAIT_MS, true);
|
|
165
|
+
if (waitMs > 0) {
|
|
166
|
+
await waitForVoices(synthesis, waitMs);
|
|
167
|
+
voices = readVoices(synthesis);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return pickLocalVoice(voices, wanted);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function errorCode(event: unknown): string | undefined {
|
|
174
|
+
const code = event && typeof event === 'object' ? (event as { error?: unknown }).error : undefined;
|
|
175
|
+
return typeof code === 'string' ? code : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function cancelQueue(synthesis: VoiceSpeechSynthesis): void {
|
|
179
|
+
try {
|
|
180
|
+
synthesis.cancel();
|
|
181
|
+
} catch {
|
|
182
|
+
// 忽略:只是尽力清队列。
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 以 ABORTED 收尾本模块全部进行中的朗读(不 cancel()),返回它们所在的 synthesis。 */
|
|
187
|
+
function supersedeOwnSpeech(): Set<VoiceSpeechSynthesis> {
|
|
188
|
+
const syntheses = new Set<VoiceSpeechSynthesis>();
|
|
189
|
+
for (const own of [...ownSpeech.values()]) {
|
|
190
|
+
syntheses.add(own.synthesis);
|
|
191
|
+
own.supersede();
|
|
192
|
+
}
|
|
193
|
+
return syntheses;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 取消本模块发起、仍在进行的浏览器朗读,被取消的调用以 `ABORTED` 拒绝。
|
|
198
|
+
* `playSpeech` 在后端音频起播前调用,免得两种来源同时出声。本模块没有进行中的朗读时什么都不做、
|
|
199
|
+
* 不访问 speechSynthesis:从没用过浏览器朗读的页面,后端路径照旧不碰它。
|
|
200
|
+
*/
|
|
201
|
+
export function cancelOwnBrowserSpeech(): void {
|
|
202
|
+
for (const synthesis of supersedeOwnSpeech()) cancelQueue(synthesis);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 用浏览器本地音色朗读,读完(end)才 resolve `'spoken'`。
|
|
207
|
+
*
|
|
208
|
+
* - 起播判据是 `start` 事件:start 之前出错、start 之前就 end、或 speak() 之后 startTimeoutMs 内没有 start
|
|
209
|
+
* (部分 Android WebView 的 speak() 静默不出声、不触发 start;iOS 首次 speak 不在用户手势内时不出声),
|
|
210
|
+
* 都 resolve `'unavailable'` 交给调用方降级到后端;看门狗到时先 cancel(),免得迟到的起播与后端音频叠在一起。
|
|
211
|
+
* - start 之后出错 → `PLAYBACK_FAILED`(不降级,避免从头重播)。
|
|
212
|
+
* - signal 中止 → cancel() 并以 `ABORTED` 拒绝;error 为 `interrupted` / `canceled`(被新的朗读或其它代码打断)
|
|
213
|
+
* 同样 `ABORTED`,但不再 cancel():此时队列里可能已是打断它的那条新 utterance。
|
|
214
|
+
* - 新的调用取代本模块尚未收尾的旧调用:旧调用以 `ABORTED` 拒绝(不再降级出声),它的看门狗与 signal 随之撤掉,
|
|
215
|
+
* 不会事后 cancel() 掉新调用正在读的 utterance。
|
|
216
|
+
*
|
|
217
|
+
* iOS 要求首次 speak() 发生在用户手势内:在点击处理里直接调用,队列为空时 speak() 之前本函数不插入异步等待。
|
|
218
|
+
*/
|
|
219
|
+
export async function speakWithBrowserVoice(
|
|
220
|
+
text: string,
|
|
221
|
+
options: SpeakWithBrowserVoiceOptions,
|
|
222
|
+
): Promise<BrowserSpeechOutcome> {
|
|
223
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
224
|
+
throw new TypeError('text must be a non-empty string.');
|
|
225
|
+
}
|
|
226
|
+
const signal = options.signal;
|
|
227
|
+
if (signal?.aborted) throw new VoiceError('ABORTED', 'Speech was aborted.');
|
|
228
|
+
const { speechSynthesis: synthesis, SpeechSynthesisUtterance: Utterance } = resolveSpeechEnvironment(
|
|
229
|
+
options.environment,
|
|
230
|
+
);
|
|
231
|
+
if (!synthesis || typeof synthesis.speak !== 'function' || typeof Utterance !== 'function') {
|
|
232
|
+
return 'unavailable';
|
|
233
|
+
}
|
|
234
|
+
let utterance: SpeechSynthesisUtterance;
|
|
235
|
+
try {
|
|
236
|
+
utterance = new Utterance(text);
|
|
237
|
+
utterance.voice = options.voice;
|
|
238
|
+
utterance.lang = options.lang;
|
|
239
|
+
utterance.rate = clampRate(options.rate);
|
|
240
|
+
} catch {
|
|
241
|
+
return 'unavailable';
|
|
242
|
+
}
|
|
243
|
+
const startTimeoutMs = delayOr(options.startTimeoutMs, START_TIMEOUT_MS, false);
|
|
244
|
+
// 旧调用的 utterance 若还在队列里,下面按 speaking / pending 清掉;这里只收尾它们的 Promise。
|
|
245
|
+
supersedeOwnSpeech();
|
|
246
|
+
|
|
247
|
+
return new Promise<BrowserSpeechOutcome>((resolve, reject) => {
|
|
248
|
+
let started = false;
|
|
249
|
+
let settled = false;
|
|
250
|
+
// 推迟中的 speak(),或 speak() 之后的起播看门狗。
|
|
251
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
252
|
+
|
|
253
|
+
const cleanup = () => {
|
|
254
|
+
settled = true;
|
|
255
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
256
|
+
timer = undefined;
|
|
257
|
+
utterance.onstart = null;
|
|
258
|
+
utterance.onend = null;
|
|
259
|
+
utterance.onerror = null;
|
|
260
|
+
signal?.removeEventListener('abort', onAbort);
|
|
261
|
+
ownSpeech.delete(utterance);
|
|
262
|
+
};
|
|
263
|
+
const finish = (outcome: BrowserSpeechOutcome, cancel = false) => {
|
|
264
|
+
if (settled) return;
|
|
265
|
+
cleanup();
|
|
266
|
+
if (cancel) cancelQueue(synthesis);
|
|
267
|
+
resolve(outcome);
|
|
268
|
+
};
|
|
269
|
+
const fail = (error: VoiceError, cancel: boolean) => {
|
|
270
|
+
if (settled) return;
|
|
271
|
+
cleanup();
|
|
272
|
+
if (cancel) cancelQueue(synthesis);
|
|
273
|
+
reject(error);
|
|
274
|
+
};
|
|
275
|
+
function onAbort() {
|
|
276
|
+
fail(new VoiceError('ABORTED', 'Speech was aborted.'), true);
|
|
277
|
+
}
|
|
278
|
+
const speakNow = () => {
|
|
279
|
+
if (settled) return;
|
|
280
|
+
timer = setTimeout(() => finish('unavailable', true), startTimeoutMs);
|
|
281
|
+
try {
|
|
282
|
+
synthesis.speak(utterance);
|
|
283
|
+
} catch {
|
|
284
|
+
finish('unavailable', true);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
utterance.onstart = () => {
|
|
289
|
+
if (settled) return;
|
|
290
|
+
started = true;
|
|
291
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
292
|
+
timer = undefined;
|
|
293
|
+
};
|
|
294
|
+
utterance.onend = () => finish(started ? 'spoken' : 'unavailable');
|
|
295
|
+
// error 取值 interrupted / canceled 表示被打断(cancel()、其它 utterance 抢占),
|
|
296
|
+
// 其余取值(synthesis-failed、audio-busy、voice-unavailable、not-allowed 等)表示失败。
|
|
297
|
+
utterance.onerror = (event) => {
|
|
298
|
+
const code = errorCode(event);
|
|
299
|
+
if (code === 'interrupted' || code === 'canceled') {
|
|
300
|
+
fail(new VoiceError('ABORTED', 'Speech was interrupted.', { cause: code }), false);
|
|
301
|
+
} else if (!started) {
|
|
302
|
+
finish('unavailable');
|
|
303
|
+
} else {
|
|
304
|
+
fail(new VoiceError('PLAYBACK_FAILED', 'Browser speech synthesis failed.', { cause: code }), false);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
308
|
+
ownSpeech.set(utterance, {
|
|
309
|
+
synthesis,
|
|
310
|
+
supersede: () => fail(new VoiceError('ABORTED', 'Speech was interrupted by a newer speech.'), false),
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
try {
|
|
314
|
+
// 队列卡住(上一条没读完,或 Chrome 在线音色长文本截断后 speaking 一直为 true)时新的 speak() 只会排队不出声:
|
|
315
|
+
// 先 cancel() 清掉。两者都报 false(队列为空)时跳过,不做无谓的 cancel。
|
|
316
|
+
const speaking = synthesis.speaking;
|
|
317
|
+
const pending = synthesis.pending;
|
|
318
|
+
if (speaking === false && pending === false) {
|
|
319
|
+
speakNow();
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
cancelQueue(synthesis);
|
|
323
|
+
if (speaking !== true && pending !== true) {
|
|
324
|
+
// 实现没报告队列状态:照旧同步 speak(),不拿手势冒险。
|
|
325
|
+
speakNow();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
// 确有朗读在队列里:部分实现会把紧跟在 cancel() 之后、同一段同步代码里 speak() 的 utterance 一并清掉
|
|
329
|
+
// (Mozilla bug 1522074 / crbug 924503),于是推迟到下一个宏任务再 speak(),看门狗从真正 speak() 时起算。
|
|
330
|
+
// 推迟不丢手势:队列非空说明本页已有 speak() 过了手势闸门(WebKit 在手势内首次 speak() 时即撤掉该限制,
|
|
331
|
+
// Chrome 看的是文档级的粘性激活)。
|
|
332
|
+
timer = setTimeout(speakNow, 0);
|
|
333
|
+
} catch {
|
|
334
|
+
finish('unavailable', true);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
}
|
|
@@ -1,72 +1,294 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import {
|
|
2
|
+
AUDIO_SNIFF_BYTES,
|
|
3
|
+
sniffAudioContainer,
|
|
4
|
+
type AudioContainer,
|
|
5
|
+
} from '../shared/audio-format';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 录音格式候选,按优先级排列:
|
|
9
|
+
* - webm/opus:Chrome、Edge、Firefox、Android WebView,Safari 18.4+ 也支持;
|
|
10
|
+
* - mp4/aac:Safari(含 iOS 14.3+),Chrome 126+ 也支持但排在 webm 之后;
|
|
11
|
+
* - ogg/opus:旧版 Firefox。
|
|
12
|
+
* 服务端按文件头魔数识别容器,这里只决定向浏览器要哪种编码。
|
|
13
|
+
*/
|
|
14
|
+
export const VOICE_RECORDING_MIME_TYPES = [
|
|
15
|
+
'audio/webm;codecs=opus',
|
|
16
|
+
'audio/mp4;codecs=mp4a.40.2',
|
|
17
|
+
'audio/mp4',
|
|
18
|
+
'audio/ogg;codecs=opus',
|
|
19
|
+
'audio/webm',
|
|
20
|
+
'audio/ogg',
|
|
21
|
+
] as const;
|
|
22
|
+
|
|
23
|
+
export interface VoiceMediaDevices {
|
|
24
|
+
getUserMedia?(constraints?: MediaStreamConstraints): Promise<MediaStream>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface VoiceNavigator {
|
|
28
|
+
mediaDevices?: VoiceMediaDevices;
|
|
6
29
|
}
|
|
7
30
|
|
|
8
|
-
export interface
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
31
|
+
export interface VoiceMediaRecorderConstructor {
|
|
32
|
+
new (stream: MediaStream, options?: MediaRecorderOptions): MediaRecorder;
|
|
33
|
+
isTypeSupported?(type: string): boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type VoiceAudioContextConstructor = new () => AudioContext;
|
|
37
|
+
|
|
38
|
+
export type VoiceAudioConstructor = new (src?: string) => HTMLAudioElement;
|
|
39
|
+
|
|
40
|
+
/** 浏览器朗读引擎(Web Speech API 的 SpeechSynthesis)里本包用到的部分。 */
|
|
41
|
+
export interface VoiceSpeechSynthesis {
|
|
42
|
+
readonly speaking?: boolean;
|
|
43
|
+
readonly pending?: boolean;
|
|
44
|
+
getVoices(): SpeechSynthesisVoice[];
|
|
45
|
+
speak(utterance: SpeechSynthesisUtterance): void;
|
|
46
|
+
cancel(): void;
|
|
47
|
+
addEventListener?(type: 'voiceschanged', listener: () => void): void;
|
|
48
|
+
removeEventListener?(type: 'voiceschanged', listener: () => void): void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type VoiceSpeechUtteranceConstructor = new (text?: string) => SpeechSynthesisUtterance;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 可注入的浏览器环境(测试替身、内置 WebView 桥接)。
|
|
55
|
+
* 显式给出的键(即便值为 undefined)覆盖全局;未给出的键取 globalThis。
|
|
56
|
+
*/
|
|
57
|
+
export interface VoiceEnvironment {
|
|
58
|
+
navigator?: VoiceNavigator;
|
|
59
|
+
MediaRecorder?: VoiceMediaRecorderConstructor;
|
|
60
|
+
AudioContext?: VoiceAudioContextConstructor;
|
|
61
|
+
Audio?: VoiceAudioConstructor;
|
|
62
|
+
isSecureContext?: boolean;
|
|
63
|
+
/** 朗读引擎;缺省 globalThis.speechSynthesis,只在浏览器朗读路径上按需读取(见 resolveSpeechEnvironment)。 */
|
|
64
|
+
speechSynthesis?: VoiceSpeechSynthesis;
|
|
65
|
+
SpeechSynthesisUtterance?: VoiceSpeechUtteranceConstructor;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface ResolvedVoiceEnvironment {
|
|
69
|
+
navigator: VoiceNavigator | undefined;
|
|
70
|
+
MediaRecorder: VoiceMediaRecorderConstructor | undefined;
|
|
71
|
+
AudioContext: VoiceAudioContextConstructor | undefined;
|
|
72
|
+
Audio: VoiceAudioConstructor | undefined;
|
|
73
|
+
isSecureContext: boolean | undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface ResolvedSpeechEnvironment {
|
|
77
|
+
speechSynthesis: VoiceSpeechSynthesis | undefined;
|
|
78
|
+
SpeechSynthesisUtterance: VoiceSpeechUtteranceConstructor | undefined;
|
|
12
79
|
}
|
|
13
80
|
|
|
14
81
|
export interface VoiceCapabilities {
|
|
82
|
+
/** 是否安全上下文(HTTPS 或 localhost);浏览器未报告时按 true 处理。 */
|
|
83
|
+
secureContext: boolean;
|
|
84
|
+
getUserMedia: boolean;
|
|
85
|
+
mediaRecorder: boolean;
|
|
86
|
+
/** MediaRecorder 将使用的格式;undefined 表示交给浏览器默认格式。 */
|
|
87
|
+
recordingMimeType?: string;
|
|
88
|
+
/** 无 MediaRecorder 时是否可走 Web Audio PCM 回退(客户端编码 16kHz WAV;要有 AudioContext 且其原型上有 createScriptProcessor)。 */
|
|
89
|
+
pcmFallback: boolean;
|
|
15
90
|
recording: boolean;
|
|
16
91
|
playback: boolean;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
92
|
+
playableFormats: { wav: boolean; mp3: boolean };
|
|
93
|
+
/**
|
|
94
|
+
* 浏览器朗读 API(speechSynthesis + SpeechSynthesisUtterance)是否存在。只表示 API 在,
|
|
95
|
+
* 不代表有可用的本地音色——那要异步 findLocalBrowserVoice 判断。缺失不算限制:朗读默认走后端。
|
|
96
|
+
*/
|
|
97
|
+
speechSynthesis: boolean;
|
|
22
98
|
limitations: string[];
|
|
23
99
|
}
|
|
24
100
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
101
|
+
type VoiceGlobal = typeof globalThis & {
|
|
102
|
+
webkitAudioContext?: VoiceAudioContextConstructor;
|
|
103
|
+
isSecureContext?: boolean;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
function isGiven(environment: VoiceEnvironment, key: keyof VoiceEnvironment): boolean {
|
|
107
|
+
return Object.prototype.hasOwnProperty.call(environment, key);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function resolveVoiceEnvironment(
|
|
111
|
+
environment: VoiceEnvironment = {},
|
|
112
|
+
): ResolvedVoiceEnvironment {
|
|
113
|
+
const scope = globalThis as VoiceGlobal;
|
|
114
|
+
const given = (key: keyof VoiceEnvironment) => isGiven(environment, key);
|
|
115
|
+
return {
|
|
116
|
+
navigator: given('navigator')
|
|
117
|
+
? environment.navigator
|
|
118
|
+
: typeof navigator === 'undefined' ? undefined : navigator,
|
|
119
|
+
MediaRecorder: given('MediaRecorder')
|
|
120
|
+
? environment.MediaRecorder
|
|
121
|
+
: typeof MediaRecorder === 'undefined' ? undefined : MediaRecorder,
|
|
122
|
+
// iOS Safari 14.5 以前只有带前缀的 webkitAudioContext。
|
|
123
|
+
AudioContext: given('AudioContext')
|
|
124
|
+
? environment.AudioContext
|
|
125
|
+
: scope.AudioContext ?? scope.webkitAudioContext,
|
|
126
|
+
Audio: given('Audio')
|
|
127
|
+
? environment.Audio
|
|
128
|
+
: typeof Audio === 'undefined' ? undefined : Audio,
|
|
129
|
+
isSecureContext: given('isSecureContext')
|
|
130
|
+
? environment.isSecureContext
|
|
131
|
+
: scope.isSecureContext,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
31
134
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
135
|
+
/**
|
|
136
|
+
* 朗读 API 单独解析、用到才取:window.speechSynthesis 是浏览器按需创建的平台对象,
|
|
137
|
+
* 录音与后端播放路径(resolveVoiceEnvironment)不去读它。
|
|
138
|
+
*/
|
|
139
|
+
export function resolveSpeechEnvironment(
|
|
140
|
+
environment: VoiceEnvironment = {},
|
|
141
|
+
): ResolvedSpeechEnvironment {
|
|
142
|
+
return {
|
|
143
|
+
speechSynthesis: isGiven(environment, 'speechSynthesis')
|
|
144
|
+
? environment.speechSynthesis
|
|
145
|
+
: typeof speechSynthesis === 'undefined' ? undefined : speechSynthesis,
|
|
146
|
+
SpeechSynthesisUtterance: isGiven(environment, 'SpeechSynthesisUtterance')
|
|
147
|
+
? environment.SpeechSynthesisUtterance
|
|
148
|
+
: typeof SpeechSynthesisUtterance === 'undefined' ? undefined : SpeechSynthesisUtterance,
|
|
40
149
|
};
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 只判断朗读 API 在不在;全局用 `in` 探测,不触发 speechSynthesis 的 getter(理由同 resolveSpeechEnvironment)。 */
|
|
153
|
+
function detectSpeechSynthesis(environment: VoiceEnvironment = {}): boolean {
|
|
154
|
+
const synthesis = isGiven(environment, 'speechSynthesis')
|
|
155
|
+
? typeof environment.speechSynthesis?.speak === 'function'
|
|
156
|
+
: 'speechSynthesis' in globalThis;
|
|
157
|
+
const Utterance = isGiven(environment, 'SpeechSynthesisUtterance')
|
|
158
|
+
? environment.SpeechSynthesisUtterance
|
|
159
|
+
: typeof SpeechSynthesisUtterance === 'undefined' ? undefined : SpeechSynthesisUtterance;
|
|
160
|
+
return synthesis && typeof Utterance === 'function';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 从候选中挑第一个浏览器声明支持的录音格式。
|
|
165
|
+
* isTypeSupported 缺失(旧 Safari、部分 WebView)时返回 undefined,交给浏览器默认格式;
|
|
166
|
+
* 个别内置 WebView 对未知类型直接抛错,所以逐个 try/catch。
|
|
167
|
+
*/
|
|
168
|
+
export function pickRecordingMimeType(
|
|
169
|
+
isTypeSupported?: (type: string) => boolean,
|
|
170
|
+
candidates: readonly string[] = VOICE_RECORDING_MIME_TYPES,
|
|
171
|
+
): string | undefined {
|
|
172
|
+
if (typeof isTypeSupported !== 'function') return undefined;
|
|
173
|
+
for (const candidate of candidates) {
|
|
174
|
+
try {
|
|
175
|
+
if (isTypeSupported(candidate)) return candidate;
|
|
176
|
+
} catch {
|
|
177
|
+
// 当作不支持,继续尝试下一个候选。
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function readBlobBytes(blob: Blob): Promise<Uint8Array> {
|
|
184
|
+
if (typeof blob.arrayBuffer === 'function') return new Uint8Array(await blob.arrayBuffer());
|
|
185
|
+
// Safari 14 以前与 jsdom 的 Blob 没有 arrayBuffer()。
|
|
186
|
+
return new Promise<Uint8Array>((resolve, reject) => {
|
|
187
|
+
const reader = new FileReader();
|
|
188
|
+
reader.onerror = () => reject(reader.error);
|
|
189
|
+
reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
|
|
190
|
+
reader.readAsArrayBuffer(blob);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 读 Blob 文件头按魔数判定容器;读失败或无法识别返回 undefined。 */
|
|
195
|
+
export async function sniffBlobContainer(blob: Blob): Promise<AudioContainer | undefined> {
|
|
196
|
+
if (!blob.size) return undefined;
|
|
197
|
+
try {
|
|
198
|
+
return sniffAudioContainer(await readBlobBytes(blob.slice(0, AUDIO_SNIFF_BYTES)));
|
|
199
|
+
} catch {
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* PCM 回退要用 ScriptProcessor:个别内置 WebView 有 AudioContext 却删掉了已废弃的 createScriptProcessor,
|
|
206
|
+
* 录音器在那里会报 UNSUPPORTED。与录音器同一口径,按原型上有没有该方法判定(不为探测而新建 AudioContext)。
|
|
207
|
+
*/
|
|
208
|
+
function supportsScriptProcessor(Context: VoiceAudioContextConstructor | undefined): boolean {
|
|
209
|
+
if (!Context) return false;
|
|
210
|
+
try {
|
|
211
|
+
const prototype = (Context as { prototype?: { createScriptProcessor?: unknown } }).prototype;
|
|
212
|
+
return typeof prototype?.createScriptProcessor === 'function';
|
|
213
|
+
} catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function probePlayableFormats(AudioCtor: VoiceAudioConstructor | undefined) {
|
|
219
|
+
if (!AudioCtor) return { wav: false, mp3: false };
|
|
220
|
+
try {
|
|
221
|
+
const probe = new AudioCtor();
|
|
222
|
+
const canPlay = (type: string) => {
|
|
223
|
+
try {
|
|
224
|
+
return probe.canPlayType(type) !== '';
|
|
225
|
+
} catch {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
return {
|
|
230
|
+
wav: canPlay('audio/wav') || canPlay('audio/wav; codecs="1"') || canPlay('audio/x-wav'),
|
|
231
|
+
mp3: canPlay('audio/mpeg'),
|
|
232
|
+
};
|
|
233
|
+
} catch {
|
|
234
|
+
return { wav: false, mp3: false };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 只做特性检测,不看 UA;limitations 用中文短句说明当前环境的限制。 */
|
|
239
|
+
export function detectVoiceCapabilities(environment?: VoiceEnvironment): VoiceCapabilities {
|
|
240
|
+
const env = resolveVoiceEnvironment(environment);
|
|
241
|
+
const secureContext = env.isSecureContext !== false;
|
|
242
|
+
const getUserMedia = typeof env.navigator?.mediaDevices?.getUserMedia === 'function';
|
|
243
|
+
const Recorder = typeof env.MediaRecorder === 'function' ? env.MediaRecorder : undefined;
|
|
244
|
+
const mediaRecorder = Boolean(Recorder);
|
|
245
|
+
const recordingMimeType = Recorder
|
|
246
|
+
? pickRecordingMimeType(
|
|
247
|
+
typeof Recorder.isTypeSupported === 'function'
|
|
248
|
+
? (type) => Recorder.isTypeSupported!(type)
|
|
249
|
+
: undefined,
|
|
250
|
+
)
|
|
251
|
+
: undefined;
|
|
252
|
+
const Context = typeof env.AudioContext === 'function' ? env.AudioContext : undefined;
|
|
253
|
+
const pcmFallback = !mediaRecorder && supportsScriptProcessor(Context);
|
|
254
|
+
const recording = secureContext && getUserMedia && (mediaRecorder || pcmFallback);
|
|
255
|
+
const playback = typeof env.Audio === 'function';
|
|
256
|
+
const playableFormats = probePlayableFormats(playback ? env.Audio : undefined);
|
|
257
|
+
const speechSynthesis = detectSpeechSynthesis(environment);
|
|
50
258
|
const limitations: string[] = [];
|
|
51
259
|
|
|
52
|
-
if (!
|
|
53
|
-
limitations.push('
|
|
260
|
+
if (!secureContext) {
|
|
261
|
+
limitations.push('页面不在安全上下文(HTTPS 或 localhost)中,浏览器不开放麦克风。');
|
|
262
|
+
} else if (!getUserMedia) {
|
|
263
|
+
limitations.push('浏览器未提供麦克风采集接口(getUserMedia),无法录音。');
|
|
54
264
|
}
|
|
55
|
-
if (!mediaRecorder &&
|
|
56
|
-
limitations.push(
|
|
265
|
+
if (!mediaRecorder && pcmFallback) {
|
|
266
|
+
limitations.push(
|
|
267
|
+
'浏览器不支持 MediaRecorder,录音走 Web Audio PCM 回退(客户端编码 16kHz WAV),须在用户手势中开始录音。',
|
|
268
|
+
);
|
|
269
|
+
} else if (!mediaRecorder && Context) {
|
|
270
|
+
limitations.push('浏览器不支持 MediaRecorder,Web Audio 也没有 ScriptProcessor,无法录音。');
|
|
271
|
+
} else if (!mediaRecorder) {
|
|
272
|
+
limitations.push('浏览器既无 MediaRecorder 也无 Web Audio,无法录音。');
|
|
273
|
+
} else if (!recordingMimeType) {
|
|
274
|
+
limitations.push('无法探测 MediaRecorder 支持的格式,录音使用浏览器默认格式(以文件头判定)。');
|
|
57
275
|
}
|
|
58
|
-
if (
|
|
59
|
-
limitations.push('
|
|
276
|
+
if (!playback) {
|
|
277
|
+
limitations.push('浏览器不支持 HTMLAudioElement,无法播放合成语音。');
|
|
278
|
+
} else if (!playableFormats.wav && !playableFormats.mp3) {
|
|
279
|
+
limitations.push('浏览器未声明可播放 WAV 或 MP3,合成语音可能无法播放。');
|
|
60
280
|
}
|
|
61
281
|
|
|
62
282
|
return {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
mediaRecorder
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
283
|
+
secureContext,
|
|
284
|
+
getUserMedia,
|
|
285
|
+
mediaRecorder,
|
|
286
|
+
...(recordingMimeType ? { recordingMimeType } : {}),
|
|
287
|
+
pcmFallback,
|
|
288
|
+
recording,
|
|
289
|
+
playback,
|
|
290
|
+
playableFormats,
|
|
291
|
+
speechSynthesis,
|
|
70
292
|
limitations,
|
|
71
293
|
};
|
|
72
294
|
}
|