soma-voice 1.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 +85 -0
- package/manifest.md +11 -0
- package/package.json +61 -0
- package/src/api/service/index.ts +5 -0
- package/src/api/service/voice/Synthesize.ts +15 -0
- package/src/api/service/voice/Transcribe.ts +16 -0
- package/src/api/service/voice/synthesize/Stream.ts +15 -0
- package/src/api/service/voice/transcribe/Raw.ts +15 -0
- package/src/client/audio-conversion.ts +127 -0
- package/src/client/audio-processing.ts +153 -0
- package/src/client/browser-codec.ts +73 -0
- package/src/client/capabilities.ts +72 -0
- package/src/client/errors.ts +10 -0
- package/src/client/http.ts +237 -0
- package/src/client/index.ts +15 -0
- package/src/client/indexeddb-storage.ts +109 -0
- package/src/client/offline.ts +139 -0
- package/src/client/player.ts +117 -0
- package/src/client/realtime-stt.ts +261 -0
- package/src/client/recorder.ts +280 -0
- package/src/client/storage.ts +89 -0
- package/src/client/streaming-tts.ts +156 -0
- package/src/client/transports.ts +221 -0
- package/src/client/wav.ts +58 -0
- package/src/index.ts +1 -0
- package/src/server/concurrency.ts +75 -0
- package/src/server/config.ts +173 -0
- package/src/server/errors.ts +49 -0
- package/src/server/index.ts +9 -0
- package/src/server/raw-transcription.ts +70 -0
- package/src/server/runtime.ts +425 -0
- package/src/server/speech-stream.ts +176 -0
- package/src/server/streaming.ts +160 -0
- package/src/server/upload.ts +94 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { VoiceError } from './errors';
|
|
2
|
+
|
|
3
|
+
export interface VoiceRequestOptions {
|
|
4
|
+
fetch?: typeof fetch;
|
|
5
|
+
basePath?: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface TranscriptionWord {
|
|
11
|
+
text: string;
|
|
12
|
+
startMs?: number;
|
|
13
|
+
endMs?: number;
|
|
14
|
+
speaker?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface TranscriptionSegment {
|
|
18
|
+
text: string;
|
|
19
|
+
startMs?: number;
|
|
20
|
+
endMs?: number;
|
|
21
|
+
speaker?: string;
|
|
22
|
+
words?: TranscriptionWord[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface TranscriptionResult {
|
|
26
|
+
text: string;
|
|
27
|
+
language?: string;
|
|
28
|
+
durationMs?: number;
|
|
29
|
+
segments?: TranscriptionSegment[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface TranscriptionOptions extends VoiceRequestOptions {
|
|
33
|
+
fileName?: string;
|
|
34
|
+
language?: string;
|
|
35
|
+
prompt?: string;
|
|
36
|
+
responseFormat?: 'json' | 'verbose_json';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type ResponseReader<T> = (response: Response) => Promise<T>;
|
|
40
|
+
|
|
41
|
+
async function request<T>(
|
|
42
|
+
url: string,
|
|
43
|
+
init: RequestInit,
|
|
44
|
+
options: VoiceRequestOptions,
|
|
45
|
+
read: ResponseReader<T>,
|
|
46
|
+
): Promise<T> {
|
|
47
|
+
if (options.signal?.aborted) {
|
|
48
|
+
throw new VoiceError('ABORTED', 'Voice request was aborted.');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
let timedOut = false;
|
|
53
|
+
const timeout = setTimeout(() => {
|
|
54
|
+
timedOut = true;
|
|
55
|
+
controller.abort();
|
|
56
|
+
}, options.timeoutMs ?? 30_000);
|
|
57
|
+
const abort = () => controller.abort();
|
|
58
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const response = await (options.fetch ?? globalThis.fetch)(`${options.basePath ?? ''}${url}`, {
|
|
62
|
+
...init,
|
|
63
|
+
signal: controller.signal,
|
|
64
|
+
});
|
|
65
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
66
|
+
controller.signal.addEventListener('abort', () => {
|
|
67
|
+
void response.body?.cancel().catch(() => undefined);
|
|
68
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
69
|
+
}, { once: true });
|
|
70
|
+
});
|
|
71
|
+
return await Promise.race([read(response), aborted]);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error instanceof VoiceError) throw error;
|
|
74
|
+
if (timedOut) throw new VoiceError('TIMEOUT', 'Voice request timed out.', error);
|
|
75
|
+
if (options.signal?.aborted) throw new VoiceError('ABORTED', 'Voice request was aborted.', error);
|
|
76
|
+
throw new VoiceError('NETWORK_ERROR', 'Voice request failed.', error);
|
|
77
|
+
} finally {
|
|
78
|
+
clearTimeout(timeout);
|
|
79
|
+
options.signal?.removeEventListener('abort', abort);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function extensionForMime(mimeType: string): string {
|
|
84
|
+
const mime = mimeType.toLowerCase().split(';', 1)[0];
|
|
85
|
+
return ({
|
|
86
|
+
'audio/wav': 'wav',
|
|
87
|
+
'audio/x-wav': 'wav',
|
|
88
|
+
'audio/mpeg': 'mp3',
|
|
89
|
+
'audio/mp3': 'mp3',
|
|
90
|
+
'audio/webm': 'webm',
|
|
91
|
+
'audio/ogg': 'ogg',
|
|
92
|
+
'audio/mp4': 'm4a',
|
|
93
|
+
'audio/aac': 'aac',
|
|
94
|
+
'audio/flac': 'flac',
|
|
95
|
+
} as Record<string, string>)[mime] ?? 'bin';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isBlobLike(value: unknown): value is Blob {
|
|
99
|
+
if (!value || typeof value !== 'object') return false;
|
|
100
|
+
const candidate = value as Partial<Blob>;
|
|
101
|
+
return typeof candidate.size === 'number'
|
|
102
|
+
&& typeof candidate.type === 'string'
|
|
103
|
+
&& typeof candidate.slice === 'function';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function parseTranscriptionResult(value: unknown): TranscriptionResult | undefined {
|
|
107
|
+
if (!value || typeof value !== 'object') return undefined;
|
|
108
|
+
const source = value as Record<string, unknown>;
|
|
109
|
+
if (typeof source.text !== 'string') return undefined;
|
|
110
|
+
const segmentSource = Array.isArray(source.segments) ? source.segments : undefined;
|
|
111
|
+
const segments = segmentSource?.flatMap((segment) => {
|
|
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(
|
|
145
|
+
audio: Blob,
|
|
146
|
+
options: TranscriptionOptions = {},
|
|
147
|
+
): Promise<TranscriptionResult> {
|
|
148
|
+
if (!isBlobLike(audio) || !audio.size) throw new TypeError('audio must be a non-empty Blob');
|
|
149
|
+
const body = new FormData();
|
|
150
|
+
body.append('file', audio, options.fileName ?? `recording.${extensionForMime(audio.type)}`);
|
|
151
|
+
if (options.language) body.append('language', options.language);
|
|
152
|
+
if (options.prompt) body.append('prompt', options.prompt);
|
|
153
|
+
if (options.responseFormat) body.append('response_format', options.responseFormat);
|
|
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');
|
|
186
|
+
}
|
|
187
|
+
const headers = new Headers({ 'content-type': audio.type });
|
|
188
|
+
if (options.language) headers.set('x-voice-language', options.language);
|
|
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', {
|
|
192
|
+
method: 'POST',
|
|
193
|
+
headers,
|
|
194
|
+
body: audio,
|
|
195
|
+
}, options, async (response) => {
|
|
196
|
+
const json = await response.json().catch(() => null) as {
|
|
197
|
+
success?: boolean;
|
|
198
|
+
message?: string;
|
|
199
|
+
msg?: string;
|
|
200
|
+
data?: unknown;
|
|
201
|
+
} | null;
|
|
202
|
+
const result = parseTranscriptionResult(json?.data);
|
|
203
|
+
if (!response.ok || !json?.success || !result) {
|
|
204
|
+
throw new VoiceError(
|
|
205
|
+
'API_ERROR',
|
|
206
|
+
json?.message ?? json?.msg ?? `Raw transcription failed (${response.status})`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
return result;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function synthesizeSpeech(
|
|
214
|
+
input: string | { text: string; voice?: string; format?: string; speed?: number },
|
|
215
|
+
options: VoiceRequestOptions = {},
|
|
216
|
+
): Promise<Blob> {
|
|
217
|
+
const payload = typeof input === 'string' ? { text: input } : input;
|
|
218
|
+
return request('/api/voice/synthesize', {
|
|
219
|
+
method: 'POST',
|
|
220
|
+
headers: { 'content-type': 'application/json' },
|
|
221
|
+
body: JSON.stringify(payload),
|
|
222
|
+
}, options, async (response) => {
|
|
223
|
+
if (!response.ok) {
|
|
224
|
+
const json = await response.json().catch(() => null) as { message?: string; msg?: string } | null;
|
|
225
|
+
throw new VoiceError(
|
|
226
|
+
'API_ERROR',
|
|
227
|
+
json?.message ?? json?.msg ?? `Speech synthesis failed (${response.status})`,
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
231
|
+
if (!contentType.startsWith('audio/')) {
|
|
232
|
+
await response.body?.cancel().catch(() => undefined);
|
|
233
|
+
throw new VoiceError('API_ERROR', 'Speech synthesis returned a non-audio response.');
|
|
234
|
+
}
|
|
235
|
+
return response.blob();
|
|
236
|
+
});
|
|
237
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './audio-conversion';
|
|
2
|
+
export * from './audio-processing';
|
|
3
|
+
export * from './browser-codec';
|
|
4
|
+
export * from './capabilities';
|
|
5
|
+
export * from './errors';
|
|
6
|
+
export * from './http';
|
|
7
|
+
export * from './indexeddb-storage';
|
|
8
|
+
export * from './offline';
|
|
9
|
+
export * from './player';
|
|
10
|
+
export * from './realtime-stt';
|
|
11
|
+
export * from './recorder';
|
|
12
|
+
export * from './storage';
|
|
13
|
+
export * from './streaming-tts';
|
|
14
|
+
export * from './transports';
|
|
15
|
+
export * from './wav';
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { VoiceStorageAdapter, VoiceStoredItem } from './storage';
|
|
2
|
+
|
|
3
|
+
interface VoiceStoreRecord extends Omit<VoiceStoredItem, 'value'> {
|
|
4
|
+
value: Blob | string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function throwIfAborted(signal?: AbortSignal): void {
|
|
8
|
+
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function requestResult<T>(request: IDBRequest<T>, signal?: AbortSignal): Promise<T> {
|
|
12
|
+
throwIfAborted(signal);
|
|
13
|
+
return new Promise<T>((resolve, reject) => {
|
|
14
|
+
let settled = false;
|
|
15
|
+
const finish = (action: () => void) => {
|
|
16
|
+
if (settled) return;
|
|
17
|
+
settled = true;
|
|
18
|
+
signal?.removeEventListener('abort', abort);
|
|
19
|
+
action();
|
|
20
|
+
};
|
|
21
|
+
const abort = () => {
|
|
22
|
+
try {
|
|
23
|
+
request.transaction?.abort();
|
|
24
|
+
} catch {
|
|
25
|
+
// The transaction may already be complete.
|
|
26
|
+
}
|
|
27
|
+
finish(() => reject(new DOMException('Aborted', 'AbortError')));
|
|
28
|
+
};
|
|
29
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
30
|
+
request.onsuccess = () => finish(() => resolve(request.result));
|
|
31
|
+
request.onerror = () => finish(() => reject(
|
|
32
|
+
request.error ?? new Error('IndexedDB request failed.'),
|
|
33
|
+
));
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function createIndexedDbVoiceStorage(options: {
|
|
38
|
+
databaseName?: string;
|
|
39
|
+
storeName?: string;
|
|
40
|
+
version?: number;
|
|
41
|
+
indexedDB?: IDBFactory;
|
|
42
|
+
} = {}): VoiceStorageAdapter & { close(): void } {
|
|
43
|
+
const factory = options.indexedDB ?? (typeof indexedDB === 'undefined' ? undefined : indexedDB);
|
|
44
|
+
if (!factory) throw new TypeError('IndexedDB is unavailable.');
|
|
45
|
+
const storeName = options.storeName ?? 'voice-items';
|
|
46
|
+
let databasePromise: Promise<IDBDatabase> | undefined;
|
|
47
|
+
|
|
48
|
+
const database = () => {
|
|
49
|
+
databasePromise ??= new Promise<IDBDatabase>((resolve, reject) => {
|
|
50
|
+
const request = factory.open(options.databaseName ?? 'soma-voice', options.version ?? 1);
|
|
51
|
+
request.onupgradeneeded = () => {
|
|
52
|
+
if (!request.result.objectStoreNames.contains(storeName)) {
|
|
53
|
+
const store = request.result.createObjectStore(storeName, { keyPath: 'id' });
|
|
54
|
+
store.createIndex('createdAt', 'createdAt');
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
request.onsuccess = () => resolve(request.result);
|
|
58
|
+
request.onerror = () => reject(request.error ?? new Error('Unable to open voice database.'));
|
|
59
|
+
request.onblocked = () => reject(new Error('Voice database upgrade is blocked.'));
|
|
60
|
+
});
|
|
61
|
+
return databasePromise;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const store = async (mode: IDBTransactionMode) => {
|
|
65
|
+
const db = await database();
|
|
66
|
+
return db.transaction(storeName, mode).objectStore(storeName);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
async save(item, saveOptions) {
|
|
71
|
+
throwIfAborted(saveOptions?.signal);
|
|
72
|
+
const actualBytes = typeof item.value === 'string'
|
|
73
|
+
? new TextEncoder().encode(item.value).byteLength
|
|
74
|
+
: item.value.size;
|
|
75
|
+
if (item.bytes !== actualBytes) throw new TypeError('Voice item byte count does not match value.');
|
|
76
|
+
await requestResult((await store('readwrite')).put(item as VoiceStoreRecord), saveOptions?.signal);
|
|
77
|
+
},
|
|
78
|
+
async load(id, loadOptions) {
|
|
79
|
+
const result = await requestResult(
|
|
80
|
+
(await store('readonly')).get(id) as IDBRequest<VoiceStoreRecord | undefined>,
|
|
81
|
+
loadOptions?.signal,
|
|
82
|
+
);
|
|
83
|
+
return result;
|
|
84
|
+
},
|
|
85
|
+
async list(listOptions) {
|
|
86
|
+
const result = await requestResult(
|
|
87
|
+
(await store('readonly')).getAll() as IDBRequest<VoiceStoreRecord[]>,
|
|
88
|
+
listOptions?.signal,
|
|
89
|
+
);
|
|
90
|
+
return result.sort((left, right) => right.createdAt - left.createdAt || left.id.localeCompare(right.id));
|
|
91
|
+
},
|
|
92
|
+
async delete(id, deleteOptions) {
|
|
93
|
+
const existing = await requestResult(
|
|
94
|
+
(await store('readonly')).getKey(id) as IDBRequest<IDBValidKey | undefined>,
|
|
95
|
+
deleteOptions?.signal,
|
|
96
|
+
);
|
|
97
|
+
if (existing === undefined) return false;
|
|
98
|
+
await requestResult((await store('readwrite')).delete(id), deleteOptions?.signal);
|
|
99
|
+
return true;
|
|
100
|
+
},
|
|
101
|
+
async clear(clearOptions) {
|
|
102
|
+
await requestResult((await store('readwrite')).clear(), clearOptions?.signal);
|
|
103
|
+
},
|
|
104
|
+
close() {
|
|
105
|
+
void databasePromise?.then((db) => db.close());
|
|
106
|
+
databasePromise = undefined;
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { VoiceError } from './errors';
|
|
2
|
+
import type { RealtimeTranscriptWord } from './realtime-stt';
|
|
3
|
+
|
|
4
|
+
export interface OfflineInitializationOptions {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
onProgress?: (progress: number) => void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface OfflineTranscriptionResult {
|
|
10
|
+
text: string;
|
|
11
|
+
language?: string;
|
|
12
|
+
segments?: Array<{
|
|
13
|
+
text: string;
|
|
14
|
+
startMs?: number;
|
|
15
|
+
endMs?: number;
|
|
16
|
+
speaker?: string;
|
|
17
|
+
words?: RealtimeTranscriptWord[];
|
|
18
|
+
}>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface OfflineSttAdapter {
|
|
22
|
+
initialize(options?: OfflineInitializationOptions): Promise<void>;
|
|
23
|
+
transcribe(audio: Blob, options?: { signal?: AbortSignal }): Promise<OfflineTranscriptionResult>;
|
|
24
|
+
dispose(): Promise<void> | void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface OfflineTtsAdapter {
|
|
28
|
+
initialize(options?: OfflineInitializationOptions): Promise<void>;
|
|
29
|
+
synthesize(
|
|
30
|
+
text: string,
|
|
31
|
+
options?: { signal?: AbortSignal; voice?: string },
|
|
32
|
+
): Promise<Blob>;
|
|
33
|
+
dispose(): Promise<void> | void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface OfflineEngineAdapter {
|
|
37
|
+
initialize(options?: OfflineInitializationOptions): Promise<void>;
|
|
38
|
+
dispose(): Promise<void> | void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function throwIfAborted(signal: AbortSignal | undefined, message: string): void {
|
|
42
|
+
if (signal?.aborted) throw new VoiceError('ABORTED', message, signal.reason);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function createOfflineEngine<
|
|
46
|
+
TAdapter extends OfflineEngineAdapter,
|
|
47
|
+
TInput,
|
|
48
|
+
TOptions extends { signal?: AbortSignal },
|
|
49
|
+
TResult,
|
|
50
|
+
>(
|
|
51
|
+
adapter: TAdapter,
|
|
52
|
+
execute: (adapter: TAdapter, input: TInput, options?: TOptions) => Promise<TResult>,
|
|
53
|
+
) {
|
|
54
|
+
let initialized = false;
|
|
55
|
+
let destroyed = false;
|
|
56
|
+
let initialization: Promise<void> | undefined;
|
|
57
|
+
|
|
58
|
+
const initialize = async (options: OfflineInitializationOptions = {}) => {
|
|
59
|
+
if (destroyed) throw new VoiceError('INVALID_STATE', 'Offline engine is destroyed.');
|
|
60
|
+
throwIfAborted(options.signal, 'Offline initialization aborted.');
|
|
61
|
+
if (initialized) return;
|
|
62
|
+
initialization ??= adapter.initialize(options)
|
|
63
|
+
.then(() => {
|
|
64
|
+
throwIfAborted(options.signal, 'Offline initialization aborted.');
|
|
65
|
+
initialized = true;
|
|
66
|
+
})
|
|
67
|
+
.catch((error) => {
|
|
68
|
+
initialization = undefined;
|
|
69
|
+
if (error instanceof VoiceError) throw error;
|
|
70
|
+
throwIfAborted(options.signal, 'Offline initialization aborted.');
|
|
71
|
+
throw new VoiceError('CAPTURE_FAILED', 'Offline engine initialization failed.', error);
|
|
72
|
+
});
|
|
73
|
+
await initialization;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const run = async (input: TInput, options?: TOptions): Promise<TResult> => {
|
|
77
|
+
if (destroyed) throw new VoiceError('INVALID_STATE', 'Offline engine is destroyed.');
|
|
78
|
+
throwIfAborted(options?.signal, 'Offline operation aborted.');
|
|
79
|
+
await initialize({ signal: options?.signal });
|
|
80
|
+
throwIfAborted(options?.signal, 'Offline operation aborted.');
|
|
81
|
+
try {
|
|
82
|
+
const result = await execute(adapter, input, options);
|
|
83
|
+
throwIfAborted(options?.signal, 'Offline operation aborted.');
|
|
84
|
+
return result;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error instanceof VoiceError) throw error;
|
|
87
|
+
throwIfAborted(options?.signal, 'Offline operation aborted.');
|
|
88
|
+
throw new VoiceError('CAPTURE_FAILED', 'Offline voice operation failed.', error);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const destroy = async () => {
|
|
93
|
+
if (destroyed) return;
|
|
94
|
+
destroyed = true;
|
|
95
|
+
await initialization?.catch(() => undefined);
|
|
96
|
+
try {
|
|
97
|
+
await adapter.dispose();
|
|
98
|
+
} finally {
|
|
99
|
+
initialized = false;
|
|
100
|
+
initialization = undefined;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
return { initialize, run, destroy };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createOfflineTranscriber(adapter: OfflineSttAdapter) {
|
|
108
|
+
const engine = createOfflineEngine<
|
|
109
|
+
OfflineSttAdapter,
|
|
110
|
+
Blob,
|
|
111
|
+
{ signal?: AbortSignal },
|
|
112
|
+
OfflineTranscriptionResult
|
|
113
|
+
>(adapter, (current, audio, options) => current.transcribe(audio, options));
|
|
114
|
+
return {
|
|
115
|
+
initialize: engine.initialize,
|
|
116
|
+
transcribe(audio: Blob, options?: { signal?: AbortSignal }) {
|
|
117
|
+
if (!audio.size) throw new TypeError('audio must be a non-empty Blob.');
|
|
118
|
+
return engine.run(audio, options);
|
|
119
|
+
},
|
|
120
|
+
destroy: engine.destroy,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function createOfflineSynthesizer(adapter: OfflineTtsAdapter) {
|
|
125
|
+
const engine = createOfflineEngine<
|
|
126
|
+
OfflineTtsAdapter,
|
|
127
|
+
string,
|
|
128
|
+
{ signal?: AbortSignal; voice?: string },
|
|
129
|
+
Blob
|
|
130
|
+
>(adapter, (current, text, options) => current.synthesize(text, options));
|
|
131
|
+
return {
|
|
132
|
+
initialize: engine.initialize,
|
|
133
|
+
synthesize(text: string, options?: { signal?: AbortSignal; voice?: string }) {
|
|
134
|
+
if (!text.trim()) throw new TypeError('text must not be empty.');
|
|
135
|
+
return engine.run(text, options);
|
|
136
|
+
},
|
|
137
|
+
destroy: engine.destroy,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { VoicePlaybackAdapter } from './capabilities';
|
|
2
|
+
import { VoiceError } from './errors';
|
|
3
|
+
|
|
4
|
+
export interface AudioPlayer {
|
|
5
|
+
play(audio: Blob, options?: { signal?: AbortSignal }): Promise<void>;
|
|
6
|
+
stop(): Promise<void>;
|
|
7
|
+
destroy(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function createAudioPlayer(options: {
|
|
11
|
+
adapter?: VoicePlaybackAdapter;
|
|
12
|
+
audioFactory?: () => HTMLAudioElement;
|
|
13
|
+
url?: Pick<typeof URL, 'createObjectURL' | 'revokeObjectURL'>;
|
|
14
|
+
} = {}): AudioPlayer {
|
|
15
|
+
let element: HTMLAudioElement | undefined;
|
|
16
|
+
let objectUrl: string | undefined;
|
|
17
|
+
let destroyed = false;
|
|
18
|
+
let playbackSignal: AbortSignal | undefined;
|
|
19
|
+
let abortListener: (() => void) | undefined;
|
|
20
|
+
let endedListener: (() => void) | undefined;
|
|
21
|
+
let errorListener: (() => void) | undefined;
|
|
22
|
+
const urls = options.url ?? (typeof URL === 'undefined' ? undefined : URL);
|
|
23
|
+
|
|
24
|
+
const detach = () => {
|
|
25
|
+
if (playbackSignal && abortListener) playbackSignal.removeEventListener('abort', abortListener);
|
|
26
|
+
if (element && endedListener) element.removeEventListener('ended', endedListener);
|
|
27
|
+
if (element && errorListener) element.removeEventListener('error', errorListener);
|
|
28
|
+
playbackSignal = undefined;
|
|
29
|
+
abortListener = undefined;
|
|
30
|
+
endedListener = undefined;
|
|
31
|
+
errorListener = undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const release = () => {
|
|
35
|
+
detach();
|
|
36
|
+
element?.pause();
|
|
37
|
+
element?.removeAttribute('src');
|
|
38
|
+
element?.load();
|
|
39
|
+
element = undefined;
|
|
40
|
+
if (objectUrl) urls?.revokeObjectURL(objectUrl);
|
|
41
|
+
objectUrl = undefined;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const stop = async () => {
|
|
45
|
+
try {
|
|
46
|
+
await options.adapter?.stop();
|
|
47
|
+
} finally {
|
|
48
|
+
release();
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const play = async (audio: Blob, playOptions: { signal?: AbortSignal } = {}) => {
|
|
53
|
+
if (destroyed) throw new VoiceError('INVALID_STATE', 'Audio player is destroyed.');
|
|
54
|
+
await stop();
|
|
55
|
+
if (playOptions.signal?.aborted) throw new VoiceError('ABORTED', 'Playback was aborted.');
|
|
56
|
+
|
|
57
|
+
playbackSignal = playOptions.signal;
|
|
58
|
+
abortListener = () => { void stop(); };
|
|
59
|
+
playbackSignal?.addEventListener('abort', abortListener, { once: true });
|
|
60
|
+
|
|
61
|
+
if (options.adapter) {
|
|
62
|
+
try {
|
|
63
|
+
await options.adapter.play(audio, playOptions);
|
|
64
|
+
return;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
release();
|
|
67
|
+
throw new VoiceError('PLAYBACK_FAILED', 'Adapter playback failed.', error);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!urls || (typeof Audio === 'undefined' && !options.audioFactory)) {
|
|
71
|
+
release();
|
|
72
|
+
throw new VoiceError('UNSUPPORTED', 'Audio playback is unavailable.');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
objectUrl = urls.createObjectURL(audio);
|
|
76
|
+
element = options.audioFactory?.() ?? new Audio();
|
|
77
|
+
element.src = objectUrl;
|
|
78
|
+
endedListener = release;
|
|
79
|
+
errorListener = release;
|
|
80
|
+
element.addEventListener('ended', endedListener, { once: true });
|
|
81
|
+
element.addEventListener('error', errorListener, { once: true });
|
|
82
|
+
try {
|
|
83
|
+
await element.play();
|
|
84
|
+
} catch (error) {
|
|
85
|
+
release();
|
|
86
|
+
const denied = error instanceof DOMException && error.name === 'NotAllowedError';
|
|
87
|
+
throw new VoiceError(
|
|
88
|
+
denied ? 'PLAYBACK_BLOCKED' : 'PLAYBACK_FAILED',
|
|
89
|
+
denied ? 'Playback requires a user gesture.' : 'Audio playback failed.',
|
|
90
|
+
error,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const destroy = async () => {
|
|
96
|
+
if (destroyed) return;
|
|
97
|
+
try {
|
|
98
|
+
await stop();
|
|
99
|
+
await options.adapter?.destroy?.();
|
|
100
|
+
} finally {
|
|
101
|
+
release();
|
|
102
|
+
destroyed = true;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
return { play, stop, destroy };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function playSpeech(
|
|
109
|
+
input: Parameters<typeof import('./http').synthesizeSpeech>[0],
|
|
110
|
+
options: Parameters<typeof import('./http').synthesizeSpeech>[1] & { player?: AudioPlayer } = {},
|
|
111
|
+
): Promise<AudioPlayer> {
|
|
112
|
+
const { synthesizeSpeech } = await import('./http');
|
|
113
|
+
const player = options.player ?? createAudioPlayer();
|
|
114
|
+
const audio = await synthesizeSpeech(input, options);
|
|
115
|
+
await player.play(audio, { signal: options.signal });
|
|
116
|
+
return player;
|
|
117
|
+
}
|