soma-voice 3.0.0 → 3.0.2

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.
Files changed (39) hide show
  1. package/dist/esm/api/service/index.d.ts +3 -0
  2. package/dist/esm/api/service/index.js +7 -0
  3. package/dist/esm/api/service/voice/Synthesize.d.ts +6 -0
  4. package/dist/esm/api/service/voice/Synthesize.js +16 -0
  5. package/dist/esm/api/service/voice/Transcribe.d.ts +6 -0
  6. package/dist/esm/api/service/voice/Transcribe.js +16 -0
  7. package/dist/esm/client/browser-voice.d.ts +53 -0
  8. package/dist/esm/client/browser-voice.js +219 -0
  9. package/dist/esm/client/capabilities.d.ts +95 -0
  10. package/dist/esm/client/capabilities.js +151 -0
  11. package/dist/esm/client/errors.d.ts +14 -0
  12. package/dist/esm/client/errors.js +16 -0
  13. package/dist/esm/client/http.d.ts +35 -0
  14. package/dist/esm/client/http.js +164 -0
  15. package/dist/esm/client/index.d.ts +9 -0
  16. package/dist/esm/client/index.js +9 -0
  17. package/dist/esm/client/player.d.ts +66 -0
  18. package/dist/esm/client/player.js +281 -0
  19. package/dist/esm/client/recorder.d.ts +43 -0
  20. package/dist/esm/client/recorder.js +499 -0
  21. package/dist/esm/client/wav.d.ts +7 -0
  22. package/dist/esm/client/wav.js +65 -0
  23. package/dist/esm/index.d.ts +1 -0
  24. package/dist/esm/index.js +1 -0
  25. package/dist/esm/server/concurrency.d.ts +3 -0
  26. package/dist/esm/server/concurrency.js +62 -0
  27. package/dist/esm/server/config.d.ts +32 -0
  28. package/dist/esm/server/config.js +167 -0
  29. package/dist/esm/server/errors.d.ts +21 -0
  30. package/dist/esm/server/errors.js +53 -0
  31. package/dist/esm/server/index.d.ts +5 -0
  32. package/dist/esm/server/index.js +5 -0
  33. package/dist/esm/server/runtime.d.ts +19 -0
  34. package/dist/esm/server/runtime.js +390 -0
  35. package/dist/esm/shared/audio-format.d.ts +16 -0
  36. package/dist/esm/shared/audio-format.js +75 -0
  37. package/dist/esm/shared/transcription.d.ts +26 -0
  38. package/dist/esm/shared/transcription.js +53 -0
  39. package/package.json +20 -17
@@ -0,0 +1,3 @@
1
+ import 'server-only';
2
+ export { default as VoiceTranscribeService } from './voice/Transcribe.js';
3
+ export { default as VoiceSynthesizeService } from './voice/Synthesize.js';
@@ -0,0 +1,7 @@
1
+ import "server-only";
2
+ import { default as default2 } from "./voice/Transcribe.js";
3
+ import { default as default3 } from "./voice/Synthesize.js";
4
+ export {
5
+ default3 as VoiceSynthesizeService,
6
+ default2 as VoiceTranscribeService
7
+ };
@@ -0,0 +1,6 @@
1
+ import 'server-only';
2
+ import type { IService } from 'soma-core';
3
+ /** `POST /api/voice/synthesize`:JSON 文本 → 音频字节(失败时为 SOMA 错误信封)。 */
4
+ export default class SynthesizeService implements IService {
5
+ post(req: Request): Promise<Response>;
6
+ }
@@ -0,0 +1,16 @@
1
+ import "server-only";
2
+ import { loadVoiceConfig } from "../../../server/config.js";
3
+ import { errorResponse } from "../../../server/errors.js";
4
+ import { synthesize } from "../../../server/runtime.js";
5
+ class SynthesizeService {
6
+ async post(req) {
7
+ try {
8
+ return await synthesize(req, loadVoiceConfig());
9
+ } catch (error) {
10
+ return errorResponse(error);
11
+ }
12
+ }
13
+ }
14
+ export {
15
+ SynthesizeService as default
16
+ };
@@ -0,0 +1,6 @@
1
+ import 'server-only';
2
+ import type { IService } from 'soma-core';
3
+ /** `POST /api/voice/transcribe`:multipart 音频 → SOMA 信封包裹的转写结果。 */
4
+ export default class TranscribeService implements IService {
5
+ post(req: Request): Promise<Response>;
6
+ }
@@ -0,0 +1,16 @@
1
+ import "server-only";
2
+ import { loadVoiceConfig } from "../../../server/config.js";
3
+ import { errorResponse, successResponse } from "../../../server/errors.js";
4
+ import { transcribe } from "../../../server/runtime.js";
5
+ class TranscribeService {
6
+ async post(req) {
7
+ try {
8
+ return successResponse(await transcribe(req, loadVoiceConfig()));
9
+ } catch (error) {
10
+ return errorResponse(error);
11
+ }
12
+ }
13
+ }
14
+ export {
15
+ TranscribeService as default
16
+ };
@@ -0,0 +1,53 @@
1
+ import { type VoiceEnvironment } from './capabilities.js';
2
+ /**
3
+ * 朗读来源:
4
+ * - `'server'`(默认):Host 后端合成,各设备音色一致;
5
+ * - `'browser-first'`:先用浏览器的本地系统音色,没有合适音色或起播失败时自动降级到后端。
6
+ * 识别不在此列,始终走后端。
7
+ */
8
+ export type SpeechVoiceSource = 'server' | 'browser-first';
9
+ /** `'spoken'`:已完整读完;`'unavailable'`:没能起播,调用方应降级到后端。 */
10
+ export type BrowserSpeechOutcome = 'spoken' | 'unavailable';
11
+ export interface FindLocalBrowserVoiceOptions {
12
+ environment?: VoiceEnvironment;
13
+ /** getVoices() 为空时等待 voiceschanged 的上限,默认 1000ms;0 表示不等。 */
14
+ waitMs?: number;
15
+ }
16
+ export interface SpeakWithBrowserVoiceOptions {
17
+ voice: SpeechSynthesisVoice;
18
+ /** BCP-47 语言标签;与 voice 一并设在 utterance 上(部分 Android 浏览器按 lang 而非 voice 选音色)。 */
19
+ lang: string;
20
+ /** 语速,夹在 0.5–2;缺省 1。 */
21
+ rate?: number;
22
+ signal?: AbortSignal;
23
+ environment?: VoiceEnvironment;
24
+ /** 起播看门狗:speak() 后这么久仍没有 start 事件就判为不可用,默认 2000ms。 */
25
+ startTimeoutMs?: number;
26
+ }
27
+ /**
28
+ * 找一个匹配 lang 的浏览器本地音色:先精确匹配(`zh-CN`),再匹配主子标签(`zh`);
29
+ * 粤语(`zh-HK`、`zh-MO`、`yue`)与普通话在主子标签一档互不匹配。
30
+ * 没有朗读 API、音色列表为空或只有在线音色时返回 undefined。
31
+ */
32
+ export declare function findLocalBrowserVoice(lang: string, options?: FindLocalBrowserVoiceOptions): Promise<SpeechSynthesisVoice | undefined>;
33
+ /**
34
+ * 取消本模块发起、仍在进行的浏览器朗读,被取消的调用以 `ABORTED` 拒绝。
35
+ * `playSpeech` 在后端音频起播前调用,免得两种来源同时出声。本模块没有进行中的朗读时什么都不做、
36
+ * 不访问 speechSynthesis:从没用过浏览器朗读的页面,后端路径照旧不碰它。
37
+ */
38
+ export declare function cancelOwnBrowserSpeech(): void;
39
+ /**
40
+ * 用浏览器本地音色朗读,读完(end)才 resolve `'spoken'`。
41
+ *
42
+ * - 起播判据是 `start` 事件:start 之前出错、start 之前就 end、或 speak() 之后 startTimeoutMs 内没有 start
43
+ * (部分 Android WebView 的 speak() 静默不出声、不触发 start;iOS 首次 speak 不在用户手势内时不出声),
44
+ * 都 resolve `'unavailable'` 交给调用方降级到后端;看门狗到时先 cancel(),免得迟到的起播与后端音频叠在一起。
45
+ * - start 之后出错 → `PLAYBACK_FAILED`(不降级,避免从头重播)。
46
+ * - signal 中止 → cancel() 并以 `ABORTED` 拒绝;error 为 `interrupted` / `canceled`(被新的朗读或其它代码打断)
47
+ * 同样 `ABORTED`,但不再 cancel():此时队列里可能已是打断它的那条新 utterance。
48
+ * - 新的调用取代本模块尚未收尾的旧调用:旧调用以 `ABORTED` 拒绝(不再降级出声),它的看门狗与 signal 随之撤掉,
49
+ * 不会事后 cancel() 掉新调用正在读的 utterance。
50
+ *
51
+ * iOS 要求首次 speak() 发生在用户手势内:在点击处理里直接调用,队列为空时 speak() 之前本函数不插入异步等待。
52
+ */
53
+ export declare function speakWithBrowserVoice(text: string, options: SpeakWithBrowserVoiceOptions): Promise<BrowserSpeechOutcome>;
@@ -0,0 +1,219 @@
1
+ import {
2
+ resolveSpeechEnvironment
3
+ } from "./capabilities.js";
4
+ import { VoiceError } from "./errors.js";
5
+ const VOICES_WAIT_MS = 1e3;
6
+ const START_TIMEOUT_MS = 2e3;
7
+ const MAX_TIMEOUT_MS = 2147483647;
8
+ const MIN_RATE = 0.5;
9
+ const MAX_RATE = 2;
10
+ const ownSpeech = /* @__PURE__ */ new Map();
11
+ function normalizeLang(tag) {
12
+ return typeof tag === "string" ? tag.trim().replace(/_/g, "-").toLowerCase() : "";
13
+ }
14
+ function spokenLanguage(tag) {
15
+ const [primary = "", ...rest] = tag.split("-");
16
+ if (primary === "zh" && rest.some((subtag) => subtag === "hk" || subtag === "mo" || subtag === "yue")) {
17
+ return "yue";
18
+ }
19
+ return primary;
20
+ }
21
+ function delayOr(value, fallback, allowZero) {
22
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
23
+ if (value < 0 || !allowZero && value === 0) return fallback;
24
+ return Math.min(value, MAX_TIMEOUT_MS);
25
+ }
26
+ function clampRate(rate) {
27
+ if (typeof rate !== "number" || !Number.isFinite(rate)) return 1;
28
+ return Math.min(MAX_RATE, Math.max(MIN_RATE, rate));
29
+ }
30
+ function readVoices(synthesis) {
31
+ try {
32
+ const voices = synthesis.getVoices();
33
+ return voices ? Array.from(voices) : [];
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+ function waitForVoices(synthesis, waitMs) {
39
+ return new Promise((resolve) => {
40
+ let timer;
41
+ const done = () => {
42
+ if (timer !== void 0) clearTimeout(timer);
43
+ timer = void 0;
44
+ try {
45
+ synthesis.removeEventListener?.("voiceschanged", onChange);
46
+ } catch {
47
+ }
48
+ resolve();
49
+ };
50
+ const onChange = () => {
51
+ if (readVoices(synthesis).length) done();
52
+ };
53
+ try {
54
+ synthesis.addEventListener?.("voiceschanged", onChange);
55
+ } catch {
56
+ }
57
+ timer = setTimeout(done, waitMs);
58
+ });
59
+ }
60
+ function pickLocalVoice(voices, wanted) {
61
+ const language = spokenLanguage(wanted);
62
+ let best;
63
+ let bestScore = 0;
64
+ for (const voice of voices) {
65
+ if (!voice || voice.localService !== true) continue;
66
+ const tag = normalizeLang(voice.lang);
67
+ if (!tag) continue;
68
+ const match = tag === wanted ? 2 : spokenLanguage(tag) === language ? 1 : 0;
69
+ if (!match) continue;
70
+ const score = match * 2 + (voice.default ? 1 : 0);
71
+ if (score > bestScore) {
72
+ best = voice;
73
+ bestScore = score;
74
+ }
75
+ }
76
+ return best;
77
+ }
78
+ async function findLocalBrowserVoice(lang, options = {}) {
79
+ const wanted = normalizeLang(lang);
80
+ if (!wanted) return void 0;
81
+ const synthesis = resolveSpeechEnvironment(options.environment).speechSynthesis;
82
+ if (!synthesis || typeof synthesis.getVoices !== "function") return void 0;
83
+ let voices = readVoices(synthesis);
84
+ if (!voices.length) {
85
+ const waitMs = delayOr(options.waitMs, VOICES_WAIT_MS, true);
86
+ if (waitMs > 0) {
87
+ await waitForVoices(synthesis, waitMs);
88
+ voices = readVoices(synthesis);
89
+ }
90
+ }
91
+ return pickLocalVoice(voices, wanted);
92
+ }
93
+ function errorCode(event) {
94
+ const code = event && typeof event === "object" ? event.error : void 0;
95
+ return typeof code === "string" ? code : void 0;
96
+ }
97
+ function cancelQueue(synthesis) {
98
+ try {
99
+ synthesis.cancel();
100
+ } catch {
101
+ }
102
+ }
103
+ function supersedeOwnSpeech() {
104
+ const syntheses = /* @__PURE__ */ new Set();
105
+ for (const own of [...ownSpeech.values()]) {
106
+ syntheses.add(own.synthesis);
107
+ own.supersede();
108
+ }
109
+ return syntheses;
110
+ }
111
+ function cancelOwnBrowserSpeech() {
112
+ for (const synthesis of supersedeOwnSpeech()) cancelQueue(synthesis);
113
+ }
114
+ async function speakWithBrowserVoice(text, options) {
115
+ if (typeof text !== "string" || !text.trim()) {
116
+ throw new TypeError("text must be a non-empty string.");
117
+ }
118
+ const signal = options.signal;
119
+ if (signal?.aborted) throw new VoiceError("ABORTED", "Speech was aborted.");
120
+ const { speechSynthesis: synthesis, SpeechSynthesisUtterance: Utterance } = resolveSpeechEnvironment(
121
+ options.environment
122
+ );
123
+ if (!synthesis || typeof synthesis.speak !== "function" || typeof Utterance !== "function") {
124
+ return "unavailable";
125
+ }
126
+ let utterance;
127
+ try {
128
+ utterance = new Utterance(text);
129
+ utterance.voice = options.voice;
130
+ utterance.lang = options.lang;
131
+ utterance.rate = clampRate(options.rate);
132
+ } catch {
133
+ return "unavailable";
134
+ }
135
+ const startTimeoutMs = delayOr(options.startTimeoutMs, START_TIMEOUT_MS, false);
136
+ supersedeOwnSpeech();
137
+ return new Promise((resolve, reject) => {
138
+ let started = false;
139
+ let settled = false;
140
+ let timer;
141
+ const cleanup = () => {
142
+ settled = true;
143
+ if (timer !== void 0) clearTimeout(timer);
144
+ timer = void 0;
145
+ utterance.onstart = null;
146
+ utterance.onend = null;
147
+ utterance.onerror = null;
148
+ signal?.removeEventListener("abort", onAbort);
149
+ ownSpeech.delete(utterance);
150
+ };
151
+ const finish = (outcome, cancel = false) => {
152
+ if (settled) return;
153
+ cleanup();
154
+ if (cancel) cancelQueue(synthesis);
155
+ resolve(outcome);
156
+ };
157
+ const fail = (error, cancel) => {
158
+ if (settled) return;
159
+ cleanup();
160
+ if (cancel) cancelQueue(synthesis);
161
+ reject(error);
162
+ };
163
+ function onAbort() {
164
+ fail(new VoiceError("ABORTED", "Speech was aborted."), true);
165
+ }
166
+ const speakNow = () => {
167
+ if (settled) return;
168
+ timer = setTimeout(() => finish("unavailable", true), startTimeoutMs);
169
+ try {
170
+ synthesis.speak(utterance);
171
+ } catch {
172
+ finish("unavailable", true);
173
+ }
174
+ };
175
+ utterance.onstart = () => {
176
+ if (settled) return;
177
+ started = true;
178
+ if (timer !== void 0) clearTimeout(timer);
179
+ timer = void 0;
180
+ };
181
+ utterance.onend = () => finish(started ? "spoken" : "unavailable");
182
+ utterance.onerror = (event) => {
183
+ const code = errorCode(event);
184
+ if (code === "interrupted" || code === "canceled") {
185
+ fail(new VoiceError("ABORTED", "Speech was interrupted.", { cause: code }), false);
186
+ } else if (!started) {
187
+ finish("unavailable");
188
+ } else {
189
+ fail(new VoiceError("PLAYBACK_FAILED", "Browser speech synthesis failed.", { cause: code }), false);
190
+ }
191
+ };
192
+ signal?.addEventListener("abort", onAbort, { once: true });
193
+ ownSpeech.set(utterance, {
194
+ synthesis,
195
+ supersede: () => fail(new VoiceError("ABORTED", "Speech was interrupted by a newer speech."), false)
196
+ });
197
+ try {
198
+ const speaking = synthesis.speaking;
199
+ const pending = synthesis.pending;
200
+ if (speaking === false && pending === false) {
201
+ speakNow();
202
+ return;
203
+ }
204
+ cancelQueue(synthesis);
205
+ if (speaking !== true && pending !== true) {
206
+ speakNow();
207
+ return;
208
+ }
209
+ timer = setTimeout(speakNow, 0);
210
+ } catch {
211
+ finish("unavailable", true);
212
+ }
213
+ });
214
+ }
215
+ export {
216
+ cancelOwnBrowserSpeech,
217
+ findLocalBrowserVoice,
218
+ speakWithBrowserVoice
219
+ };
@@ -0,0 +1,95 @@
1
+ import { type AudioContainer } from '../shared/audio-format.js';
2
+ /**
3
+ * 录音格式候选,按优先级排列:
4
+ * - webm/opus:Chrome、Edge、Firefox、Android WebView,Safari 18.4+ 也支持;
5
+ * - mp4/aac:Safari(含 iOS 14.3+),Chrome 126+ 也支持但排在 webm 之后;
6
+ * - ogg/opus:旧版 Firefox。
7
+ * 服务端按文件头魔数识别容器,这里只决定向浏览器要哪种编码。
8
+ */
9
+ export declare const VOICE_RECORDING_MIME_TYPES: readonly ["audio/webm;codecs=opus", "audio/mp4;codecs=mp4a.40.2", "audio/mp4", "audio/ogg;codecs=opus", "audio/webm", "audio/ogg"];
10
+ export interface VoiceMediaDevices {
11
+ getUserMedia?(constraints?: MediaStreamConstraints): Promise<MediaStream>;
12
+ }
13
+ export interface VoiceNavigator {
14
+ mediaDevices?: VoiceMediaDevices;
15
+ }
16
+ export interface VoiceMediaRecorderConstructor {
17
+ new (stream: MediaStream, options?: MediaRecorderOptions): MediaRecorder;
18
+ isTypeSupported?(type: string): boolean;
19
+ }
20
+ export type VoiceAudioContextConstructor = new () => AudioContext;
21
+ export type VoiceAudioConstructor = new (src?: string) => HTMLAudioElement;
22
+ /** 浏览器朗读引擎(Web Speech API 的 SpeechSynthesis)里本包用到的部分。 */
23
+ export interface VoiceSpeechSynthesis {
24
+ readonly speaking?: boolean;
25
+ readonly pending?: boolean;
26
+ getVoices(): SpeechSynthesisVoice[];
27
+ speak(utterance: SpeechSynthesisUtterance): void;
28
+ cancel(): void;
29
+ addEventListener?(type: 'voiceschanged', listener: () => void): void;
30
+ removeEventListener?(type: 'voiceschanged', listener: () => void): void;
31
+ }
32
+ export type VoiceSpeechUtteranceConstructor = new (text?: string) => SpeechSynthesisUtterance;
33
+ /**
34
+ * 可注入的浏览器环境(测试替身、内置 WebView 桥接)。
35
+ * 显式给出的键(即便值为 undefined)覆盖全局;未给出的键取 globalThis。
36
+ */
37
+ export interface VoiceEnvironment {
38
+ navigator?: VoiceNavigator;
39
+ MediaRecorder?: VoiceMediaRecorderConstructor;
40
+ AudioContext?: VoiceAudioContextConstructor;
41
+ Audio?: VoiceAudioConstructor;
42
+ isSecureContext?: boolean;
43
+ /** 朗读引擎;缺省 globalThis.speechSynthesis,只在浏览器朗读路径上按需读取(见 resolveSpeechEnvironment)。 */
44
+ speechSynthesis?: VoiceSpeechSynthesis;
45
+ SpeechSynthesisUtterance?: VoiceSpeechUtteranceConstructor;
46
+ }
47
+ export interface ResolvedVoiceEnvironment {
48
+ navigator: VoiceNavigator | undefined;
49
+ MediaRecorder: VoiceMediaRecorderConstructor | undefined;
50
+ AudioContext: VoiceAudioContextConstructor | undefined;
51
+ Audio: VoiceAudioConstructor | undefined;
52
+ isSecureContext: boolean | undefined;
53
+ }
54
+ export interface ResolvedSpeechEnvironment {
55
+ speechSynthesis: VoiceSpeechSynthesis | undefined;
56
+ SpeechSynthesisUtterance: VoiceSpeechUtteranceConstructor | undefined;
57
+ }
58
+ export interface VoiceCapabilities {
59
+ /** 是否安全上下文(HTTPS 或 localhost);浏览器未报告时按 true 处理。 */
60
+ secureContext: boolean;
61
+ getUserMedia: boolean;
62
+ mediaRecorder: boolean;
63
+ /** MediaRecorder 将使用的格式;undefined 表示交给浏览器默认格式。 */
64
+ recordingMimeType?: string;
65
+ /** 无 MediaRecorder 时是否可走 Web Audio PCM 回退(客户端编码 16kHz WAV;要有 AudioContext 且其原型上有 createScriptProcessor)。 */
66
+ pcmFallback: boolean;
67
+ recording: boolean;
68
+ playback: boolean;
69
+ playableFormats: {
70
+ wav: boolean;
71
+ mp3: boolean;
72
+ };
73
+ /**
74
+ * 浏览器朗读 API(speechSynthesis + SpeechSynthesisUtterance)是否存在。只表示 API 在,
75
+ * 不代表有可用的本地音色——那要异步 findLocalBrowserVoice 判断。缺失不算限制:朗读默认走后端。
76
+ */
77
+ speechSynthesis: boolean;
78
+ limitations: string[];
79
+ }
80
+ export declare function resolveVoiceEnvironment(environment?: VoiceEnvironment): ResolvedVoiceEnvironment;
81
+ /**
82
+ * 朗读 API 单独解析、用到才取:window.speechSynthesis 是浏览器按需创建的平台对象,
83
+ * 录音与后端播放路径(resolveVoiceEnvironment)不去读它。
84
+ */
85
+ export declare function resolveSpeechEnvironment(environment?: VoiceEnvironment): ResolvedSpeechEnvironment;
86
+ /**
87
+ * 从候选中挑第一个浏览器声明支持的录音格式。
88
+ * isTypeSupported 缺失(旧 Safari、部分 WebView)时返回 undefined,交给浏览器默认格式;
89
+ * 个别内置 WebView 对未知类型直接抛错,所以逐个 try/catch。
90
+ */
91
+ export declare function pickRecordingMimeType(isTypeSupported?: (type: string) => boolean, candidates?: readonly string[]): string | undefined;
92
+ /** 读 Blob 文件头按魔数判定容器;读失败或无法识别返回 undefined。 */
93
+ export declare function sniffBlobContainer(blob: Blob): Promise<AudioContainer | undefined>;
94
+ /** 只做特性检测,不看 UA;limitations 用中文短句说明当前环境的限制。 */
95
+ export declare function detectVoiceCapabilities(environment?: VoiceEnvironment): VoiceCapabilities;
@@ -0,0 +1,151 @@
1
+ import {
2
+ AUDIO_SNIFF_BYTES,
3
+ sniffAudioContainer
4
+ } from "../shared/audio-format.js";
5
+ const VOICE_RECORDING_MIME_TYPES = [
6
+ "audio/webm;codecs=opus",
7
+ "audio/mp4;codecs=mp4a.40.2",
8
+ "audio/mp4",
9
+ "audio/ogg;codecs=opus",
10
+ "audio/webm",
11
+ "audio/ogg"
12
+ ];
13
+ function isGiven(environment, key) {
14
+ return Object.prototype.hasOwnProperty.call(environment, key);
15
+ }
16
+ function resolveVoiceEnvironment(environment = {}) {
17
+ const scope = globalThis;
18
+ const given = (key) => isGiven(environment, key);
19
+ return {
20
+ navigator: given("navigator") ? environment.navigator : typeof navigator === "undefined" ? void 0 : navigator,
21
+ MediaRecorder: given("MediaRecorder") ? environment.MediaRecorder : typeof MediaRecorder === "undefined" ? void 0 : MediaRecorder,
22
+ // iOS Safari 14.5 以前只有带前缀的 webkitAudioContext。
23
+ AudioContext: given("AudioContext") ? environment.AudioContext : scope.AudioContext ?? scope.webkitAudioContext,
24
+ Audio: given("Audio") ? environment.Audio : typeof Audio === "undefined" ? void 0 : Audio,
25
+ isSecureContext: given("isSecureContext") ? environment.isSecureContext : scope.isSecureContext
26
+ };
27
+ }
28
+ function resolveSpeechEnvironment(environment = {}) {
29
+ return {
30
+ speechSynthesis: isGiven(environment, "speechSynthesis") ? environment.speechSynthesis : typeof speechSynthesis === "undefined" ? void 0 : speechSynthesis,
31
+ SpeechSynthesisUtterance: isGiven(environment, "SpeechSynthesisUtterance") ? environment.SpeechSynthesisUtterance : typeof SpeechSynthesisUtterance === "undefined" ? void 0 : SpeechSynthesisUtterance
32
+ };
33
+ }
34
+ function detectSpeechSynthesis(environment = {}) {
35
+ const synthesis = isGiven(environment, "speechSynthesis") ? typeof environment.speechSynthesis?.speak === "function" : "speechSynthesis" in globalThis;
36
+ const Utterance = isGiven(environment, "SpeechSynthesisUtterance") ? environment.SpeechSynthesisUtterance : typeof SpeechSynthesisUtterance === "undefined" ? void 0 : SpeechSynthesisUtterance;
37
+ return synthesis && typeof Utterance === "function";
38
+ }
39
+ function pickRecordingMimeType(isTypeSupported, candidates = VOICE_RECORDING_MIME_TYPES) {
40
+ if (typeof isTypeSupported !== "function") return void 0;
41
+ for (const candidate of candidates) {
42
+ try {
43
+ if (isTypeSupported(candidate)) return candidate;
44
+ } catch {
45
+ }
46
+ }
47
+ return void 0;
48
+ }
49
+ async function readBlobBytes(blob) {
50
+ if (typeof blob.arrayBuffer === "function") return new Uint8Array(await blob.arrayBuffer());
51
+ return new Promise((resolve, reject) => {
52
+ const reader = new FileReader();
53
+ reader.onerror = () => reject(reader.error);
54
+ reader.onload = () => resolve(new Uint8Array(reader.result));
55
+ reader.readAsArrayBuffer(blob);
56
+ });
57
+ }
58
+ async function sniffBlobContainer(blob) {
59
+ if (!blob.size) return void 0;
60
+ try {
61
+ return sniffAudioContainer(await readBlobBytes(blob.slice(0, AUDIO_SNIFF_BYTES)));
62
+ } catch {
63
+ return void 0;
64
+ }
65
+ }
66
+ function supportsScriptProcessor(Context) {
67
+ if (!Context) return false;
68
+ try {
69
+ const prototype = Context.prototype;
70
+ return typeof prototype?.createScriptProcessor === "function";
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ function probePlayableFormats(AudioCtor) {
76
+ if (!AudioCtor) return { wav: false, mp3: false };
77
+ try {
78
+ const probe = new AudioCtor();
79
+ const canPlay = (type) => {
80
+ try {
81
+ return probe.canPlayType(type) !== "";
82
+ } catch {
83
+ return false;
84
+ }
85
+ };
86
+ return {
87
+ wav: canPlay("audio/wav") || canPlay('audio/wav; codecs="1"') || canPlay("audio/x-wav"),
88
+ mp3: canPlay("audio/mpeg")
89
+ };
90
+ } catch {
91
+ return { wav: false, mp3: false };
92
+ }
93
+ }
94
+ function detectVoiceCapabilities(environment) {
95
+ const env = resolveVoiceEnvironment(environment);
96
+ const secureContext = env.isSecureContext !== false;
97
+ const getUserMedia = typeof env.navigator?.mediaDevices?.getUserMedia === "function";
98
+ const Recorder = typeof env.MediaRecorder === "function" ? env.MediaRecorder : void 0;
99
+ const mediaRecorder = Boolean(Recorder);
100
+ const recordingMimeType = Recorder ? pickRecordingMimeType(
101
+ typeof Recorder.isTypeSupported === "function" ? (type) => Recorder.isTypeSupported(type) : void 0
102
+ ) : void 0;
103
+ const Context = typeof env.AudioContext === "function" ? env.AudioContext : void 0;
104
+ const pcmFallback = !mediaRecorder && supportsScriptProcessor(Context);
105
+ const recording = secureContext && getUserMedia && (mediaRecorder || pcmFallback);
106
+ const playback = typeof env.Audio === "function";
107
+ const playableFormats = probePlayableFormats(playback ? env.Audio : void 0);
108
+ const speechSynthesis2 = detectSpeechSynthesis(environment);
109
+ const limitations = [];
110
+ if (!secureContext) {
111
+ limitations.push("\u9875\u9762\u4E0D\u5728\u5B89\u5168\u4E0A\u4E0B\u6587\uFF08HTTPS \u6216 localhost\uFF09\u4E2D\uFF0C\u6D4F\u89C8\u5668\u4E0D\u5F00\u653E\u9EA6\u514B\u98CE\u3002");
112
+ } else if (!getUserMedia) {
113
+ limitations.push("\u6D4F\u89C8\u5668\u672A\u63D0\u4F9B\u9EA6\u514B\u98CE\u91C7\u96C6\u63A5\u53E3\uFF08getUserMedia\uFF09\uFF0C\u65E0\u6CD5\u5F55\u97F3\u3002");
114
+ }
115
+ if (!mediaRecorder && pcmFallback) {
116
+ limitations.push(
117
+ "\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 MediaRecorder\uFF0C\u5F55\u97F3\u8D70 Web Audio PCM \u56DE\u9000\uFF08\u5BA2\u6237\u7AEF\u7F16\u7801 16kHz WAV\uFF09\uFF0C\u987B\u5728\u7528\u6237\u624B\u52BF\u4E2D\u5F00\u59CB\u5F55\u97F3\u3002"
118
+ );
119
+ } else if (!mediaRecorder && Context) {
120
+ limitations.push("\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 MediaRecorder\uFF0CWeb Audio \u4E5F\u6CA1\u6709 ScriptProcessor\uFF0C\u65E0\u6CD5\u5F55\u97F3\u3002");
121
+ } else if (!mediaRecorder) {
122
+ limitations.push("\u6D4F\u89C8\u5668\u65E2\u65E0 MediaRecorder \u4E5F\u65E0 Web Audio\uFF0C\u65E0\u6CD5\u5F55\u97F3\u3002");
123
+ } else if (!recordingMimeType) {
124
+ limitations.push("\u65E0\u6CD5\u63A2\u6D4B MediaRecorder \u652F\u6301\u7684\u683C\u5F0F\uFF0C\u5F55\u97F3\u4F7F\u7528\u6D4F\u89C8\u5668\u9ED8\u8BA4\u683C\u5F0F\uFF08\u4EE5\u6587\u4EF6\u5934\u5224\u5B9A\uFF09\u3002");
125
+ }
126
+ if (!playback) {
127
+ limitations.push("\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 HTMLAudioElement\uFF0C\u65E0\u6CD5\u64AD\u653E\u5408\u6210\u8BED\u97F3\u3002");
128
+ } else if (!playableFormats.wav && !playableFormats.mp3) {
129
+ limitations.push("\u6D4F\u89C8\u5668\u672A\u58F0\u660E\u53EF\u64AD\u653E WAV \u6216 MP3\uFF0C\u5408\u6210\u8BED\u97F3\u53EF\u80FD\u65E0\u6CD5\u64AD\u653E\u3002");
130
+ }
131
+ return {
132
+ secureContext,
133
+ getUserMedia,
134
+ mediaRecorder,
135
+ ...recordingMimeType ? { recordingMimeType } : {},
136
+ pcmFallback,
137
+ recording,
138
+ playback,
139
+ playableFormats,
140
+ speechSynthesis: speechSynthesis2,
141
+ limitations
142
+ };
143
+ }
144
+ export {
145
+ VOICE_RECORDING_MIME_TYPES,
146
+ detectVoiceCapabilities,
147
+ pickRecordingMimeType,
148
+ resolveSpeechEnvironment,
149
+ resolveVoiceEnvironment,
150
+ sniffBlobContainer
151
+ };
@@ -0,0 +1,14 @@
1
+ export type VoiceErrorCode = 'UNSUPPORTED' | 'INSECURE_CONTEXT' | 'INVALID_STATE' | 'PERMISSION_DENIED' | 'NO_DEVICE' | 'DEVICE_BUSY' | 'LIMIT_EXCEEDED' | 'CAPTURE_FAILED' | 'EMPTY_RECORDING' | 'ABORTED' | 'NETWORK_ERROR' | 'TIMEOUT' | 'API_ERROR' | 'PLAYBACK_BLOCKED' | 'PLAYBACK_FAILED';
2
+ export interface VoiceErrorOptions {
3
+ cause?: unknown;
4
+ /** HTTP 状态码(API_ERROR 时给出)。 */
5
+ status?: number;
6
+ /** SOMA 响应信封里的业务码(API_ERROR 时给出),如 4603。 */
7
+ serverCode?: number | string;
8
+ }
9
+ export declare class VoiceError extends Error {
10
+ readonly code: VoiceErrorCode;
11
+ readonly status?: number;
12
+ readonly serverCode?: number | string;
13
+ constructor(code: VoiceErrorCode, message: string, options?: VoiceErrorOptions);
14
+ }
@@ -0,0 +1,16 @@
1
+ class VoiceError extends Error {
2
+ code;
3
+ status;
4
+ serverCode;
5
+ constructor(code, message, options = {}) {
6
+ super(message);
7
+ this.name = "VoiceError";
8
+ this.code = code;
9
+ if (options.cause !== void 0) this.cause = options.cause;
10
+ if (options.status !== void 0) this.status = options.status;
11
+ if (options.serverCode !== void 0) this.serverCode = options.serverCode;
12
+ }
13
+ }
14
+ export {
15
+ VoiceError
16
+ };
@@ -0,0 +1,35 @@
1
+ import { type TranscriptionResult } from '../shared/transcription.js';
2
+ export interface VoiceRequestOptions {
3
+ /** 注入 fetch(测试或 Host 自带的鉴权封装);缺省 globalThis.fetch。 */
4
+ fetch?: typeof fetch;
5
+ /** 同源路由前缀(Host 挂在子路径时,如 `/app`);缺省空串。 */
6
+ basePath?: string;
7
+ signal?: AbortSignal;
8
+ timeoutMs?: number;
9
+ }
10
+ export interface TranscribeAudioOptions extends VoiceRequestOptions {
11
+ /** BCP-47 语言标签,如 `zh`、`en-US`;缺省由语音服务自动检测。 */
12
+ language?: string;
13
+ /** 转写提示词(专有名词、上下文),服务端限 1000 字符。 */
14
+ prompt?: string;
15
+ /** 是否返回词级时间戳;缺省由语音服务决定(默认开启)。 */
16
+ wordTimestamps?: boolean;
17
+ /** 覆盖上传文件名;缺省 `recording.<按魔数判定的扩展名>`。 */
18
+ fileName?: string;
19
+ }
20
+ export type SpeechFormat = 'wav' | 'mp3';
21
+ export interface SpeechSynthesisInput {
22
+ text: string;
23
+ voice?: string;
24
+ /** 缺省由 Host 配置决定(默认 wav:所有浏览器都能播)。 */
25
+ format?: SpeechFormat;
26
+ speed?: number;
27
+ }
28
+ /**
29
+ * 上传一段录音到同源 `POST /api/voice/transcribe`(Host 鉴权 hook 生效),返回结构化转写结果。
30
+ * 容器以文件头魔数为准:Safari 的 MediaRecorder.mimeType 可能为空,各浏览器 codecs 写法也不一,
31
+ * 所以文件名扩展名与 multipart part 的 Content-Type 都按魔数改写(服务端同样只认魔数)。
32
+ */
33
+ export declare function transcribeAudio(audio: Blob, options?: TranscribeAudioOptions): Promise<TranscriptionResult>;
34
+ /** 同源 `POST /api/voice/synthesize` 合成语音,返回音频 Blob(`audio/wav` 或 `audio/mpeg`)。 */
35
+ export declare function synthesizeSpeech(input: string | SpeechSynthesisInput, options?: VoiceRequestOptions): Promise<Blob>;