forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepgram.ts
More file actions
45 lines (43 loc) · 1.34 KB
/
Copy pathdeepgram.ts
File metadata and controls
45 lines (43 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { StreamingTranscriber, TranscriptHandler } from './types';
/**
* Deepgram live STT.
* React Native and browser WebSocket implementations cannot attach Authorization
* headers after construction, so callers must supply `createWebSocket`.
*/
export function createDeepgramTranscriber(options: {
apiKey: string;
sampleRate?: number;
onTranscript: TranscriptHandler;
createWebSocket: (url: string, headers: Record<string, string>) => WebSocket;
}): StreamingTranscriber {
const sampleRate = options.sampleRate ?? 16000;
const url =
`wss://api.deepgram.com/v1/listen?punctuate=true&model=nova&language=en-US` +
`&encoding=linear16&sample_rate=${sampleRate}&channels=1`;
const headers = { Authorization: `Token ${options.apiKey}` };
const ws = options.createWebSocket(url, headers);
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
try {
const data = typeof event.data === 'string' ? JSON.parse(event.data) : null;
const transcript = data?.channel?.alternatives?.[0]?.transcript;
if (transcript) options.onTranscript(transcript);
} catch {
// ignore parse errors
}
};
return {
appendPcm(chunk) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(chunk);
}
},
stop() {
try {
ws.close();
} catch {
// ignore
}
},
};
}