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
package/src/client/errors.ts
CHANGED
|
@@ -1,10 +1,28 @@
|
|
|
1
1
|
export type VoiceErrorCode =
|
|
2
|
-
| 'UNSUPPORTED' | 'INVALID_STATE' | 'PERMISSION_DENIED' | '
|
|
3
|
-
| '
|
|
4
|
-
| 'PLAYBACK_BLOCKED' | 'PLAYBACK_FAILED';
|
|
2
|
+
| 'UNSUPPORTED' | 'INSECURE_CONTEXT' | 'INVALID_STATE' | 'PERMISSION_DENIED' | 'NO_DEVICE'
|
|
3
|
+
| 'DEVICE_BUSY' | 'LIMIT_EXCEEDED' | 'CAPTURE_FAILED' | 'EMPTY_RECORDING' | 'ABORTED'
|
|
4
|
+
| 'NETWORK_ERROR' | 'TIMEOUT' | 'API_ERROR' | 'PLAYBACK_BLOCKED' | 'PLAYBACK_FAILED';
|
|
5
|
+
|
|
6
|
+
export interface VoiceErrorOptions {
|
|
7
|
+
cause?: unknown;
|
|
8
|
+
/** HTTP 状态码(API_ERROR 时给出)。 */
|
|
9
|
+
status?: number;
|
|
10
|
+
/** SOMA 响应信封里的业务码(API_ERROR 时给出),如 4603。 */
|
|
11
|
+
serverCode?: number | string;
|
|
12
|
+
}
|
|
5
13
|
|
|
6
14
|
export class VoiceError extends Error {
|
|
7
|
-
|
|
8
|
-
|
|
15
|
+
readonly code: VoiceErrorCode;
|
|
16
|
+
readonly status?: number;
|
|
17
|
+
readonly serverCode?: number | string;
|
|
18
|
+
|
|
19
|
+
constructor(code: VoiceErrorCode, message: string, options: VoiceErrorOptions = {}) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = 'VoiceError';
|
|
22
|
+
this.code = code;
|
|
23
|
+
// 显式赋值而不走 Error 构造参数:Safari 15 以前与部分内置 WebView 不认 ErrorOptions.cause。
|
|
24
|
+
if (options.cause !== undefined) this.cause = options.cause;
|
|
25
|
+
if (options.status !== undefined) this.status = options.status;
|
|
26
|
+
if (options.serverCode !== undefined) this.serverCode = options.serverCode;
|
|
9
27
|
}
|
|
10
28
|
}
|
package/src/client/http.ts
CHANGED
|
@@ -1,98 +1,169 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AUDIO_CONTAINER_EXTENSION,
|
|
3
|
+
AUDIO_CONTAINER_MIME,
|
|
4
|
+
containerFromMimeType,
|
|
5
|
+
} from '../shared/audio-format';
|
|
6
|
+
import { parseTranscriptionResult, type TranscriptionResult } from '../shared/transcription';
|
|
7
|
+
import { sniffBlobContainer } from './capabilities';
|
|
1
8
|
import { VoiceError } from './errors';
|
|
2
9
|
|
|
3
10
|
export interface VoiceRequestOptions {
|
|
11
|
+
/** 注入 fetch(测试或 Host 自带的鉴权封装);缺省 globalThis.fetch。 */
|
|
4
12
|
fetch?: typeof fetch;
|
|
13
|
+
/** 同源路由前缀(Host 挂在子路径时,如 `/app`);缺省空串。 */
|
|
5
14
|
basePath?: string;
|
|
6
15
|
signal?: AbortSignal;
|
|
7
16
|
timeoutMs?: number;
|
|
8
17
|
}
|
|
9
18
|
|
|
10
|
-
export interface
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
19
|
+
export interface TranscribeAudioOptions extends VoiceRequestOptions {
|
|
20
|
+
/** BCP-47 语言标签,如 `zh`、`en-US`;缺省由语音服务自动检测。 */
|
|
21
|
+
language?: string;
|
|
22
|
+
/** 转写提示词(专有名词、上下文),服务端限 1000 字符。 */
|
|
23
|
+
prompt?: string;
|
|
24
|
+
/** 是否返回词级时间戳;缺省由语音服务决定(默认开启)。 */
|
|
25
|
+
wordTimestamps?: boolean;
|
|
26
|
+
/** 覆盖上传文件名;缺省 `recording.<按魔数判定的扩展名>`。 */
|
|
27
|
+
fileName?: string;
|
|
15
28
|
}
|
|
16
29
|
|
|
17
|
-
export
|
|
30
|
+
export type SpeechFormat = 'wav' | 'mp3';
|
|
31
|
+
|
|
32
|
+
export interface SpeechSynthesisInput {
|
|
18
33
|
text: string;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
34
|
+
voice?: string;
|
|
35
|
+
/** 缺省由 Host 配置决定(默认 wav:所有浏览器都能播)。 */
|
|
36
|
+
format?: SpeechFormat;
|
|
37
|
+
speed?: number;
|
|
23
38
|
}
|
|
24
39
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
40
|
+
const TRANSCRIBE_TIMEOUT_MS = 120_000;
|
|
41
|
+
const SYNTHESIZE_TIMEOUT_MS = 60_000;
|
|
42
|
+
/** setTimeout 延迟的上限(2^31-1 ms):更大的值会被截断成立即触发,请求随即报 TIMEOUT。 */
|
|
43
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
44
|
+
|
|
45
|
+
interface VoiceEnvelope {
|
|
46
|
+
success?: unknown;
|
|
47
|
+
code?: unknown;
|
|
48
|
+
message?: unknown;
|
|
49
|
+
msg?: unknown;
|
|
50
|
+
data?: unknown;
|
|
30
51
|
}
|
|
31
52
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
language?: string;
|
|
35
|
-
prompt?: string;
|
|
36
|
-
responseFormat?: 'json' | 'verbose_json';
|
|
53
|
+
function routePrefix(basePath: string | undefined): string {
|
|
54
|
+
return (basePath ?? '').replace(/\/+$/, '');
|
|
37
55
|
}
|
|
38
56
|
|
|
39
|
-
|
|
57
|
+
/**
|
|
58
|
+
* 让中止真正取消底层响应体。`response.json()` / `blob()` 一开读就锁住流,此后 `response.body.cancel()`
|
|
59
|
+
* 只会被拒绝、底层来源收不到取消(注入的 fetch 不理会 signal 时,连接会一直占着)。所以读之前把响应体
|
|
60
|
+
* 接进一条带 signal 的管道:中止时由管道取消来源,读取随之以中止原因失败;来源出错(连接被重置)时
|
|
61
|
+
* 读取以同一个错误失败。无响应体或环境缺 TransformStream 时原样返回。
|
|
62
|
+
*/
|
|
63
|
+
function abortableResponse(response: Response, signal: AbortSignal): Response {
|
|
64
|
+
const body = response.body;
|
|
65
|
+
if (!body || typeof body.pipeTo !== 'function' || typeof TransformStream !== 'function') return response;
|
|
66
|
+
const pipe = new TransformStream();
|
|
67
|
+
let piped: Response;
|
|
68
|
+
try {
|
|
69
|
+
// 先建新 Response 再接管道:构造失败(状态码越界等)时原响应体还没被锁,照旧可读。
|
|
70
|
+
piped = new Response(pipe.readable, {
|
|
71
|
+
status: response.status,
|
|
72
|
+
statusText: response.statusText,
|
|
73
|
+
headers: response.headers,
|
|
74
|
+
});
|
|
75
|
+
} catch {
|
|
76
|
+
return response;
|
|
77
|
+
}
|
|
78
|
+
void body.pipeTo(pipe.writable, { signal }).catch(() => undefined);
|
|
79
|
+
return piped;
|
|
80
|
+
}
|
|
40
81
|
|
|
41
82
|
async function request<T>(
|
|
42
|
-
|
|
83
|
+
path: string,
|
|
43
84
|
init: RequestInit,
|
|
44
85
|
options: VoiceRequestOptions,
|
|
45
|
-
|
|
86
|
+
defaultTimeoutMs: number,
|
|
87
|
+
read: (response: Response) => Promise<T>,
|
|
46
88
|
): Promise<T> {
|
|
47
89
|
if (options.signal?.aborted) {
|
|
48
90
|
throw new VoiceError('ABORTED', 'Voice request was aborted.');
|
|
49
91
|
}
|
|
92
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
93
|
+
if (typeof fetchImpl !== 'function') {
|
|
94
|
+
throw new VoiceError('UNSUPPORTED', 'fetch is unavailable in this environment.');
|
|
95
|
+
}
|
|
96
|
+
const timeoutMs = typeof options.timeoutMs === 'number'
|
|
97
|
+
&& Number.isFinite(options.timeoutMs)
|
|
98
|
+
&& options.timeoutMs > 0
|
|
99
|
+
? Math.min(options.timeoutMs, MAX_TIMEOUT_MS)
|
|
100
|
+
: defaultTimeoutMs;
|
|
50
101
|
|
|
51
102
|
const controller = new AbortController();
|
|
52
103
|
let timedOut = false;
|
|
53
104
|
const timeout = setTimeout(() => {
|
|
54
105
|
timedOut = true;
|
|
55
106
|
controller.abort();
|
|
56
|
-
},
|
|
107
|
+
}, timeoutMs);
|
|
57
108
|
const abort = () => controller.abort();
|
|
58
109
|
options.signal?.addEventListener('abort', abort, { once: true });
|
|
59
110
|
|
|
60
111
|
try {
|
|
61
|
-
const response = await (
|
|
112
|
+
const response = await fetchImpl(`${routePrefix(options.basePath)}${path}`, {
|
|
62
113
|
...init,
|
|
63
114
|
signal: controller.signal,
|
|
64
115
|
});
|
|
116
|
+
if (controller.signal.aborted) {
|
|
117
|
+
// 中止之后才拿到响应(fetch 替身不理会 signal):响应体尚未上锁,直接取消后丢弃。
|
|
118
|
+
void response.body?.cancel().catch(() => undefined);
|
|
119
|
+
throw new DOMException('Aborted', 'AbortError');
|
|
120
|
+
}
|
|
121
|
+
// 超时与取消要覆盖到读响应体为止:管道负责取消底层响应体,race 让读取立即以 AbortError 结束。
|
|
122
|
+
const readable = abortableResponse(response, controller.signal);
|
|
65
123
|
const aborted = new Promise<never>((_resolve, reject) => {
|
|
66
124
|
controller.signal.addEventListener('abort', () => {
|
|
67
|
-
void response.body?.cancel().catch(() => undefined);
|
|
68
125
|
reject(new DOMException('Aborted', 'AbortError'));
|
|
69
126
|
}, { once: true });
|
|
70
127
|
});
|
|
71
|
-
return await Promise.race([read(
|
|
128
|
+
return await Promise.race([read(readable), aborted]);
|
|
72
129
|
} catch (error) {
|
|
73
130
|
if (error instanceof VoiceError) throw error;
|
|
74
|
-
if (timedOut) throw new VoiceError('TIMEOUT', 'Voice request timed out.', error);
|
|
75
|
-
if (options.signal?.aborted)
|
|
76
|
-
|
|
131
|
+
if (timedOut) throw new VoiceError('TIMEOUT', 'Voice request timed out.', { cause: error });
|
|
132
|
+
if (options.signal?.aborted) {
|
|
133
|
+
throw new VoiceError('ABORTED', 'Voice request was aborted.', { cause: error });
|
|
134
|
+
}
|
|
135
|
+
throw new VoiceError('NETWORK_ERROR', 'Voice request failed.', { cause: error });
|
|
77
136
|
} finally {
|
|
78
137
|
clearTimeout(timeout);
|
|
79
138
|
options.signal?.removeEventListener('abort', abort);
|
|
80
139
|
}
|
|
81
140
|
}
|
|
82
141
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
142
|
+
/**
|
|
143
|
+
* 读 SOMA 信封;不是 JSON 对象时返回 null,由调用方报 API_ERROR。
|
|
144
|
+
* 2xx 响应的读体失败(连接中途被重置)原样抛出,由 request() 归为 NETWORK_ERROR(与合成读音频体一致);
|
|
145
|
+
* 非 2xx 的状态码已说明失败,信封只是补充,读不到就按状态码给兜底消息。
|
|
146
|
+
*/
|
|
147
|
+
async function readEnvelope(response: Response): Promise<VoiceEnvelope | null> {
|
|
148
|
+
const text = response.ok ? await response.text() : await response.text().catch(() => '');
|
|
149
|
+
let json: unknown;
|
|
150
|
+
try {
|
|
151
|
+
json = JSON.parse(text);
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
return json && typeof json === 'object' && !Array.isArray(json) ? json as VoiceEnvelope : null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function apiError(response: Response, envelope: VoiceEnvelope | null, fallback: string): VoiceError {
|
|
159
|
+
const message = [envelope?.message, envelope?.msg]
|
|
160
|
+
.find((value): value is string => typeof value === 'string' && value.length > 0);
|
|
161
|
+
const code = envelope?.code;
|
|
162
|
+
const serverCode = typeof code === 'number' || typeof code === 'string' ? code : undefined;
|
|
163
|
+
return new VoiceError('API_ERROR', message ?? fallback, {
|
|
164
|
+
status: response.status,
|
|
165
|
+
...(serverCode !== undefined ? { serverCode } : {}),
|
|
166
|
+
});
|
|
96
167
|
}
|
|
97
168
|
|
|
98
169
|
function isBlobLike(value: unknown): value is Blob {
|
|
@@ -103,134 +174,80 @@ function isBlobLike(value: unknown): value is Blob {
|
|
|
103
174
|
&& typeof candidate.slice === 'function';
|
|
104
175
|
}
|
|
105
176
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if (!segment || typeof segment !== 'object') return [];
|
|
113
|
-
const item = segment as Record<string, unknown>;
|
|
114
|
-
if (typeof item.text !== 'string') return [];
|
|
115
|
-
const words = Array.isArray(item.words)
|
|
116
|
-
? item.words.flatMap((word) => {
|
|
117
|
-
if (!word || typeof word !== 'object') return [];
|
|
118
|
-
const entry = word as Record<string, unknown>;
|
|
119
|
-
if (typeof entry.text !== 'string') return [];
|
|
120
|
-
return [{
|
|
121
|
-
text: entry.text,
|
|
122
|
-
...(typeof entry.startMs === 'number' ? { startMs: entry.startMs } : {}),
|
|
123
|
-
...(typeof entry.endMs === 'number' ? { endMs: entry.endMs } : {}),
|
|
124
|
-
...(typeof entry.speaker === 'string' ? { speaker: entry.speaker } : {}),
|
|
125
|
-
}];
|
|
126
|
-
})
|
|
127
|
-
: undefined;
|
|
128
|
-
return [{
|
|
129
|
-
text: item.text,
|
|
130
|
-
...(typeof item.startMs === 'number' ? { startMs: item.startMs } : {}),
|
|
131
|
-
...(typeof item.endMs === 'number' ? { endMs: item.endMs } : {}),
|
|
132
|
-
...(typeof item.speaker === 'string' ? { speaker: item.speaker } : {}),
|
|
133
|
-
...(words ? { words } : {}),
|
|
134
|
-
}];
|
|
135
|
-
});
|
|
136
|
-
return {
|
|
137
|
-
text: source.text,
|
|
138
|
-
...(typeof source.language === 'string' ? { language: source.language } : {}),
|
|
139
|
-
...(typeof source.durationMs === 'number' ? { durationMs: source.durationMs } : {}),
|
|
140
|
-
...(segments ? { segments } : {}),
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export async function transcribeAudioDetailed(
|
|
177
|
+
/**
|
|
178
|
+
* 上传一段录音到同源 `POST /api/voice/transcribe`(Host 鉴权 hook 生效),返回结构化转写结果。
|
|
179
|
+
* 容器以文件头魔数为准:Safari 的 MediaRecorder.mimeType 可能为空,各浏览器 codecs 写法也不一,
|
|
180
|
+
* 所以文件名扩展名与 multipart part 的 Content-Type 都按魔数改写(服务端同样只认魔数)。
|
|
181
|
+
*/
|
|
182
|
+
export async function transcribeAudio(
|
|
145
183
|
audio: Blob,
|
|
146
|
-
options:
|
|
184
|
+
options: TranscribeAudioOptions = {},
|
|
147
185
|
): Promise<TranscriptionResult> {
|
|
148
|
-
if (!isBlobLike(audio) || !audio.size) throw new TypeError('audio must be a non-empty Blob');
|
|
186
|
+
if (!isBlobLike(audio) || !audio.size) throw new TypeError('audio must be a non-empty Blob.');
|
|
187
|
+
const declared = containerFromMimeType(audio.type);
|
|
188
|
+
const container = await sniffBlobContainer(audio) ?? declared;
|
|
189
|
+
const upload = container && container !== declared
|
|
190
|
+
? audio.slice(0, audio.size, AUDIO_CONTAINER_MIME[container])
|
|
191
|
+
: audio;
|
|
192
|
+
const extension = container ? AUDIO_CONTAINER_EXTENSION[container] : 'bin';
|
|
193
|
+
|
|
149
194
|
const body = new FormData();
|
|
150
|
-
body.append('file',
|
|
195
|
+
body.append('file', upload, options.fileName ?? `recording.${extension}`);
|
|
151
196
|
if (options.language) body.append('language', options.language);
|
|
152
197
|
if (options.prompt) body.append('prompt', options.prompt);
|
|
153
|
-
if (options.
|
|
154
|
-
|
|
155
|
-
return request('/api/voice/transcribe', { method: 'POST', body }, options, async (response) => {
|
|
156
|
-
const json = await response.json().catch(() => null) as {
|
|
157
|
-
success?: boolean;
|
|
158
|
-
message?: string;
|
|
159
|
-
msg?: string;
|
|
160
|
-
data?: unknown;
|
|
161
|
-
} | null;
|
|
162
|
-
const result = parseTranscriptionResult(json?.data);
|
|
163
|
-
if (!response.ok || !json?.success || !result) {
|
|
164
|
-
throw new VoiceError(
|
|
165
|
-
'API_ERROR',
|
|
166
|
-
json?.message ?? json?.msg ?? `Transcription failed (${response.status})`,
|
|
167
|
-
);
|
|
168
|
-
}
|
|
169
|
-
return result;
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
export async function transcribeAudio(
|
|
174
|
-
audio: Blob,
|
|
175
|
-
options: TranscriptionOptions = {},
|
|
176
|
-
): Promise<string> {
|
|
177
|
-
return (await transcribeAudioDetailed(audio, options)).text;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
export async function transcribeAudioRaw(
|
|
181
|
-
audio: Blob,
|
|
182
|
-
options: TranscriptionOptions = {},
|
|
183
|
-
): Promise<TranscriptionResult> {
|
|
184
|
-
if (!isBlobLike(audio) || !audio.size || !audio.type.toLowerCase().startsWith('audio/')) {
|
|
185
|
-
throw new TypeError('audio must be a non-empty audio Blob');
|
|
198
|
+
if (options.wordTimestamps !== undefined) {
|
|
199
|
+
body.append('word_timestamps', options.wordTimestamps ? 'true' : 'false');
|
|
186
200
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (options.prompt) headers.set('x-voice-prompt', encodeURIComponent(options.prompt));
|
|
190
|
-
if (options.responseFormat) headers.set('x-voice-response-format', options.responseFormat);
|
|
191
|
-
return request('/api/voice/transcribe/raw', {
|
|
201
|
+
|
|
202
|
+
return request('/api/voice/transcribe', {
|
|
192
203
|
method: 'POST',
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
throw new VoiceError(
|
|
205
|
-
'API_ERROR',
|
|
206
|
-
json?.message ?? json?.msg ?? `Raw transcription failed (${response.status})`,
|
|
207
|
-
);
|
|
204
|
+
body,
|
|
205
|
+
}, options, TRANSCRIBE_TIMEOUT_MS, async (response) => {
|
|
206
|
+
const envelope = await readEnvelope(response);
|
|
207
|
+
if (!response.ok || envelope?.success !== true) {
|
|
208
|
+
throw apiError(response, envelope, `Transcription failed (${response.status}).`);
|
|
209
|
+
}
|
|
210
|
+
const result = parseTranscriptionResult(envelope?.data);
|
|
211
|
+
if (!result) {
|
|
212
|
+
throw new VoiceError('API_ERROR', 'Transcription response is malformed.', {
|
|
213
|
+
status: response.status,
|
|
214
|
+
});
|
|
208
215
|
}
|
|
209
216
|
return result;
|
|
210
217
|
});
|
|
211
218
|
}
|
|
212
219
|
|
|
220
|
+
/** 同源 `POST /api/voice/synthesize` 合成语音,返回音频 Blob(`audio/wav` 或 `audio/mpeg`)。 */
|
|
213
221
|
export async function synthesizeSpeech(
|
|
214
|
-
input: string |
|
|
222
|
+
input: string | SpeechSynthesisInput,
|
|
215
223
|
options: VoiceRequestOptions = {},
|
|
216
224
|
): Promise<Blob> {
|
|
217
|
-
const
|
|
225
|
+
const source = typeof input === 'string' ? { text: input } as SpeechSynthesisInput : input;
|
|
226
|
+
if (!source || typeof source.text !== 'string' || !source.text.trim()) {
|
|
227
|
+
throw new TypeError('text must be a non-empty string.');
|
|
228
|
+
}
|
|
229
|
+
const payload = {
|
|
230
|
+
text: source.text,
|
|
231
|
+
...(source.voice !== undefined ? { voice: source.voice } : {}),
|
|
232
|
+
...(source.format !== undefined ? { format: source.format } : {}),
|
|
233
|
+
...(source.speed !== undefined ? { speed: source.speed } : {}),
|
|
234
|
+
};
|
|
235
|
+
|
|
218
236
|
return request('/api/voice/synthesize', {
|
|
219
237
|
method: 'POST',
|
|
220
238
|
headers: { 'content-type': 'application/json' },
|
|
221
239
|
body: JSON.stringify(payload),
|
|
222
|
-
}, options, async (response) => {
|
|
240
|
+
}, options, SYNTHESIZE_TIMEOUT_MS, async (response) => {
|
|
223
241
|
if (!response.ok) {
|
|
224
|
-
const
|
|
225
|
-
throw
|
|
226
|
-
'API_ERROR',
|
|
227
|
-
json?.message ?? json?.msg ?? `Speech synthesis failed (${response.status})`,
|
|
228
|
-
);
|
|
242
|
+
const envelope = await readEnvelope(response);
|
|
243
|
+
throw apiError(response, envelope, `Speech synthesis failed (${response.status}).`);
|
|
229
244
|
}
|
|
230
245
|
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
231
246
|
if (!contentType.startsWith('audio/')) {
|
|
232
247
|
await response.body?.cancel().catch(() => undefined);
|
|
233
|
-
throw new VoiceError('API_ERROR', 'Speech synthesis returned a non-audio response.'
|
|
248
|
+
throw new VoiceError('API_ERROR', 'Speech synthesis returned a non-audio response.', {
|
|
249
|
+
status: response.status,
|
|
250
|
+
});
|
|
234
251
|
}
|
|
235
252
|
return response.blob();
|
|
236
253
|
});
|
package/src/client/index.ts
CHANGED
|
@@ -1,15 +1,9 @@
|
|
|
1
|
-
export * from '
|
|
2
|
-
export * from '
|
|
3
|
-
export * from './browser-
|
|
1
|
+
export * from '../shared/audio-format';
|
|
2
|
+
export * from '../shared/transcription';
|
|
3
|
+
export * from './browser-voice';
|
|
4
4
|
export * from './capabilities';
|
|
5
5
|
export * from './errors';
|
|
6
6
|
export * from './http';
|
|
7
|
-
export * from './indexeddb-storage';
|
|
8
|
-
export * from './offline';
|
|
9
7
|
export * from './player';
|
|
10
|
-
export * from './realtime-stt';
|
|
11
8
|
export * from './recorder';
|
|
12
|
-
export * from './storage';
|
|
13
|
-
export * from './streaming-tts';
|
|
14
|
-
export * from './transports';
|
|
15
9
|
export * from './wav';
|