@amaster.ai/asr-client 1.0.0-beta.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amaster Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # @amaster.ai/asr-client
2
+
3
+ 通义千问实时语音识别(ASR)WebSocket 客户端,支持麦克风录音。
4
+
5
+ ## 特性
6
+
7
+ - ✅ 完整的 WebSocket 协议封装
8
+ - ✅ 自动麦克风采集和音频编码
9
+ - ✅ 实时流式识别结果
10
+ - ✅ VAD 自动检测语音开始/结束
11
+ - ✅ TypeScript 类型支持
12
+ - ✅ 基于实际调试验证的实现
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ npm install @amaster.ai/asr-client
18
+ ```
19
+
20
+ ## 快速开始
21
+
22
+ ```typescript
23
+ import { createASRClient } from '@amaster.ai/asr-client';
24
+
25
+ // 创建客户端
26
+ const asr = createASRClient({
27
+ gatewayUrl: 'ws://www.appok.ai/api/proxy/builtin/platform/qwen-asr-realtime/api-ws/v1/realtime',
28
+ language: 'zh',
29
+ });
30
+
31
+ // 监听事件
32
+ asr.on('session-created', (session) => {
33
+ console.log('会话创建:', session.id, session.model);
34
+ });
35
+
36
+ asr.on('speech-started', () => {
37
+ console.log('🎤 检测到语音开始');
38
+ });
39
+
40
+ asr.on('transcript-partial', ({ text }) => {
41
+ console.log('⏳ 识别中:', text);
42
+ });
43
+
44
+ asr.on('transcript-final', ({ text }) => {
45
+ console.log('✅ 识别完成:', text);
46
+ });
47
+
48
+ // 连接并开始录音
49
+ await asr.connect();
50
+ await asr.startRecording(); // 自动请求麦克风权限
51
+
52
+ // 停止录音
53
+ asr.stopRecording();
54
+
55
+ // 断开连接
56
+ asr.disconnect();
57
+ ```
58
+
59
+ ## API 文档
60
+
61
+ ### createASRClient(config)
62
+
63
+ 创建 ASR 客户端实例。
64
+
65
+ **参数**:
66
+ - `gatewayUrl`: Gateway WebSocket URL(会自动追加 model 参数)
67
+ - `language`: 识别语言,默认 `'zh'`
68
+ - `audioFormat`: 音频格式,默认 `'pcm16'`
69
+ - `sampleRate`: 采样率,默认 `16000`
70
+
71
+ ### ASRClient
72
+
73
+ #### connect()
74
+
75
+ 连接到 ASR 服务。
76
+
77
+ #### startRecording()
78
+
79
+ 开始录音识别(会请求麦克风权限)。
80
+
81
+ #### stopRecording()
82
+
83
+ 停止录音。
84
+
85
+ #### on(event, callback)
86
+
87
+ 监听事件。
88
+
89
+ **事件类型**:
90
+ - `connected`: WebSocket 连接建立
91
+ - `session-created`: 会话创建成功
92
+ - `recording-started`: 录音已开始
93
+ - `speech-started`: VAD 检测到语音开始
94
+ - `speech-stopped`: VAD 检测到语音停止
95
+ - `transcript-partial`: 中间识别结果(实时更新)
96
+ - `transcript-final`: 最终识别结果(确认)
97
+ - `error`: 发生错误
98
+ - `closed`: 连接关闭
99
+
100
+ #### disconnect()
101
+
102
+ 停止录音并断开连接。
103
+
104
+ ## 实现细节
105
+
106
+ ### 音频采集
107
+
108
+ - 采样率:16kHz
109
+ - 格式:PCM 16-bit Mono
110
+ - 编码:Base64
111
+ - 发送频率:约每秒 4 次(每次 4096 采样点)
112
+
113
+ ### WebSocket 协议
114
+
115
+ 基于实际验证的消息类型:
116
+ - `input_audio_buffer.append` - 发送音频数据
117
+
118
+ ### 识别结果
119
+
120
+ 实际事件类型(与文档不同!):
121
+ - `conversation.item.input_audio_transcription.text` - 中间结果
122
+ - `conversation.item.input_audio_transcription.completed` - 最终结果
123
+
124
+ ### VAD(语音活动检测)
125
+
126
+ 服务器自动检测:
127
+ - `input_audio_buffer.speech_started` - 开始说话
128
+ - `input_audio_buffer.speech_stopped` - 停止说话
129
+
130
+ ## License
131
+
132
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,162 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.ts
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ createASRClient: () => createASRClient
23
+ });
24
+ module.exports = __toCommonJS(index_exports);
25
+
26
+ // src/asr-client.ts
27
+ function createASRClient(config) {
28
+ const {
29
+ url,
30
+ audioFormat = "pcm16",
31
+ sampleRate = 16e3,
32
+ onReady,
33
+ onSpeechStart,
34
+ onSpeechEnd,
35
+ onTranscript,
36
+ onError
37
+ } = config;
38
+ let ws = null;
39
+ let mediaStream = null;
40
+ let audioContext = null;
41
+ let processor = null;
42
+ async function connect() {
43
+ return new Promise((resolve, reject) => {
44
+ ws = new WebSocket(url);
45
+ ws.onopen = () => {
46
+ };
47
+ ws.onmessage = (event) => {
48
+ var _a;
49
+ const data = JSON.parse(event.data);
50
+ if (data.type === "session.created") {
51
+ onReady == null ? void 0 : onReady();
52
+ resolve();
53
+ }
54
+ if (data.type === "input_audio_buffer.speech_started") {
55
+ onSpeechStart == null ? void 0 : onSpeechStart();
56
+ }
57
+ if (data.type === "input_audio_buffer.speech_stopped") {
58
+ onSpeechEnd == null ? void 0 : onSpeechEnd();
59
+ }
60
+ if (data.type === "conversation.item.input_audio_transcription.text") {
61
+ onTranscript == null ? void 0 : onTranscript(data.text || "", false);
62
+ }
63
+ if (data.type === "conversation.item.input_audio_transcription.completed") {
64
+ onTranscript == null ? void 0 : onTranscript(data.text || data.transcript || "", true);
65
+ }
66
+ if (data.type === "error") {
67
+ const err = new Error(((_a = data.error) == null ? void 0 : _a.message) || "Unknown error");
68
+ onError == null ? void 0 : onError(err);
69
+ reject(err);
70
+ }
71
+ };
72
+ ws.onerror = () => {
73
+ const err = new Error("WebSocket connection error");
74
+ onError == null ? void 0 : onError(err);
75
+ reject(err);
76
+ };
77
+ ws.onclose = () => {
78
+ ws = null;
79
+ };
80
+ });
81
+ }
82
+ async function startRecording() {
83
+ if (typeof window === "undefined") {
84
+ throw new Error("Recording only supported in browser");
85
+ }
86
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
87
+ throw new Error("WebSocket not connected");
88
+ }
89
+ try {
90
+ mediaStream = await navigator.mediaDevices.getUserMedia({
91
+ audio: {
92
+ sampleRate,
93
+ channelCount: 1,
94
+ echoCancellation: true,
95
+ noiseSuppression: true
96
+ }
97
+ });
98
+ audioContext = new AudioContext({ sampleRate });
99
+ const source = audioContext.createMediaStreamSource(mediaStream);
100
+ processor = audioContext.createScriptProcessor(4096, 1, 1);
101
+ processor.onaudioprocess = (e) => {
102
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
103
+ const inputData = e.inputBuffer.getChannelData(0);
104
+ const pcm = new Int16Array(inputData.length);
105
+ for (let i = 0; i < inputData.length; i++) {
106
+ const s = Math.max(-1, Math.min(1, inputData[i]));
107
+ pcm[i] = s < 0 ? s * 32768 : s * 32767;
108
+ }
109
+ const bytes = new Uint8Array(pcm.buffer);
110
+ let binary = "";
111
+ for (let i = 0; i < bytes.length; i++) {
112
+ binary += String.fromCharCode(bytes[i]);
113
+ }
114
+ const base64 = btoa(binary);
115
+ ws.send(JSON.stringify({
116
+ type: "input_audio_buffer.append",
117
+ audio: base64
118
+ }));
119
+ };
120
+ source.connect(processor);
121
+ processor.connect(audioContext.destination);
122
+ } catch (err) {
123
+ onError == null ? void 0 : onError(err);
124
+ throw err;
125
+ }
126
+ }
127
+ function stopRecording() {
128
+ if (mediaStream) {
129
+ mediaStream.getTracks().forEach((track) => track.stop());
130
+ mediaStream = null;
131
+ }
132
+ if (processor) {
133
+ processor.disconnect();
134
+ processor = null;
135
+ }
136
+ if (audioContext) {
137
+ audioContext.close();
138
+ audioContext = null;
139
+ }
140
+ if (ws && ws.readyState === WebSocket.OPEN) {
141
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
142
+ }
143
+ }
144
+ function close() {
145
+ stopRecording();
146
+ if (ws) {
147
+ ws.close();
148
+ ws = null;
149
+ }
150
+ }
151
+ return {
152
+ connect,
153
+ startRecording,
154
+ stopRecording,
155
+ close
156
+ };
157
+ }
158
+ // Annotate the CommonJS export names for ESM import in node:
159
+ 0 && (module.exports = {
160
+ createASRClient
161
+ });
162
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/asr-client.ts"],"sourcesContent":["export type { ASRClient, ASRClientConfig } from './asr-client';\nexport { createASRClient } from './asr-client';\n","/**\n * ASR Realtime WebSocket Client\n */\n\nexport interface ASRClientConfig {\n /** WebSocket endpoint URL */\n url: string;\n /** Audio format, default 'pcm16' */\n audioFormat?: 'pcm16' | 'g711a' | 'g711u';\n /** Sample rate, default 16000 */\n sampleRate?: number;\n /** Called when connection is ready */\n onReady?: () => void;\n /** Called when speech is detected */\n onSpeechStart?: () => void;\n /** Called when speech stops */\n onSpeechEnd?: () => void;\n /** Called on transcript result */\n onTranscript?: (text: string, isFinal: boolean) => void;\n /** Called on error */\n onError?: (error: Error) => void;\n}\n\nexport interface ASRClient {\n /** Connect to ASR service */\n connect(): Promise<void>;\n /** Start recording from microphone */\n startRecording(): Promise<void>;\n /** Stop recording */\n stopRecording(): void;\n /** Close connection */\n close(): void;\n}\n\nexport function createASRClient(config: ASRClientConfig): ASRClient {\n const {\n url,\n audioFormat = 'pcm16',\n sampleRate = 16000,\n onReady,\n onSpeechStart,\n onSpeechEnd,\n onTranscript,\n onError,\n } = config;\n\n let ws: WebSocket | null = null;\n let mediaStream: MediaStream | null = null;\n let audioContext: AudioContext | null = null;\n let processor: ScriptProcessorNode | null = null;\n\n async function connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n ws = new WebSocket(url);\n\n ws.onopen = () => {};\n\n ws.onmessage = (event) => {\n const data = JSON.parse(event.data);\n\n if (data.type === 'session.created') {\n onReady?.();\n resolve();\n }\n\n if (data.type === 'input_audio_buffer.speech_started') {\n onSpeechStart?.();\n }\n\n if (data.type === 'input_audio_buffer.speech_stopped') {\n onSpeechEnd?.();\n }\n\n if (data.type === 'conversation.item.input_audio_transcription.text') {\n onTranscript?.(data.text || '', false);\n }\n\n if (data.type === 'conversation.item.input_audio_transcription.completed') {\n onTranscript?.(data.text || data.transcript || '', true);\n }\n\n if (data.type === 'error') {\n const err = new Error(data.error?.message || 'Unknown error');\n onError?.(err);\n reject(err);\n }\n };\n\n ws.onerror = () => {\n const err = new Error('WebSocket connection error');\n onError?.(err);\n reject(err);\n };\n\n ws.onclose = () => {\n ws = null;\n };\n });\n }\n\n async function startRecording(): Promise<void> {\n if (typeof window === 'undefined') {\n throw new Error('Recording only supported in browser');\n }\n\n if (!ws || ws.readyState !== WebSocket.OPEN) {\n throw new Error('WebSocket not connected');\n }\n\n try {\n mediaStream = await navigator.mediaDevices.getUserMedia({\n audio: {\n sampleRate,\n channelCount: 1,\n echoCancellation: true,\n noiseSuppression: true,\n },\n });\n\n audioContext = new AudioContext({ sampleRate });\n const source = audioContext.createMediaStreamSource(mediaStream);\n processor = audioContext.createScriptProcessor(4096, 1, 1);\n\n processor.onaudioprocess = (e) => {\n if (!ws || ws.readyState !== WebSocket.OPEN) return;\n\n const inputData = e.inputBuffer.getChannelData(0);\n\n const pcm = new Int16Array(inputData.length);\n for (let i = 0; i < inputData.length; i++) {\n const s = Math.max(-1, Math.min(1, inputData[i]));\n pcm[i] = s < 0 ? s * 32768 : s * 32767;\n }\n\n const bytes = new Uint8Array(pcm.buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n const base64 = btoa(binary);\n\n ws.send(JSON.stringify({\n type: 'input_audio_buffer.append',\n audio: base64,\n }));\n };\n\n source.connect(processor);\n processor.connect(audioContext.destination);\n } catch (err) {\n onError?.(err as Error);\n throw err;\n }\n }\n\n function stopRecording() {\n if (mediaStream) {\n mediaStream.getTracks().forEach(track => track.stop());\n mediaStream = null;\n }\n\n if (processor) {\n processor.disconnect();\n processor = null;\n }\n\n if (audioContext) {\n audioContext.close();\n audioContext = null;\n }\n\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));\n }\n }\n\n function close() {\n stopRecording();\n if (ws) {\n ws.close();\n ws = null;\n }\n }\n\n return {\n connect,\n startRecording,\n stopRecording,\n close,\n };\n}\n"],"mappings":";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,QAAI,aAAa;AACf,kBAAY,UAAU,EAAE,QAAQ,WAAS,MAAM,KAAK,CAAC;AACrD,oBAAc;AAAA,IAChB;AAEA,QAAI,WAAW;AACb,gBAAU,WAAW;AACrB,kBAAY;AAAA,IACd;AAEA,QAAI,cAAc;AAChB,mBAAa,MAAM;AACnB,qBAAe;AAAA,IACjB;AAEA,QAAI,MAAM,GAAG,eAAe,UAAU,MAAM;AAC1C,SAAG,KAAK,KAAK,UAAU,EAAE,MAAM,4BAA4B,CAAC,CAAC;AAAA,IAC/D;AAAA,EACF;AAEA,WAAS,QAAQ;AACf,kBAAc;AACd,QAAI,IAAI;AACN,SAAG,MAAM;AACT,WAAK;AAAA,IACP;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * ASR Realtime WebSocket Client
3
+ */
4
+ interface ASRClientConfig {
5
+ /** WebSocket endpoint URL */
6
+ url: string;
7
+ /** Audio format, default 'pcm16' */
8
+ audioFormat?: 'pcm16' | 'g711a' | 'g711u';
9
+ /** Sample rate, default 16000 */
10
+ sampleRate?: number;
11
+ /** Called when connection is ready */
12
+ onReady?: () => void;
13
+ /** Called when speech is detected */
14
+ onSpeechStart?: () => void;
15
+ /** Called when speech stops */
16
+ onSpeechEnd?: () => void;
17
+ /** Called on transcript result */
18
+ onTranscript?: (text: string, isFinal: boolean) => void;
19
+ /** Called on error */
20
+ onError?: (error: Error) => void;
21
+ }
22
+ interface ASRClient {
23
+ /** Connect to ASR service */
24
+ connect(): Promise<void>;
25
+ /** Start recording from microphone */
26
+ startRecording(): Promise<void>;
27
+ /** Stop recording */
28
+ stopRecording(): void;
29
+ /** Close connection */
30
+ close(): void;
31
+ }
32
+ declare function createASRClient(config: ASRClientConfig): ASRClient;
33
+
34
+ export { type ASRClient, type ASRClientConfig, createASRClient };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * ASR Realtime WebSocket Client
3
+ */
4
+ interface ASRClientConfig {
5
+ /** WebSocket endpoint URL */
6
+ url: string;
7
+ /** Audio format, default 'pcm16' */
8
+ audioFormat?: 'pcm16' | 'g711a' | 'g711u';
9
+ /** Sample rate, default 16000 */
10
+ sampleRate?: number;
11
+ /** Called when connection is ready */
12
+ onReady?: () => void;
13
+ /** Called when speech is detected */
14
+ onSpeechStart?: () => void;
15
+ /** Called when speech stops */
16
+ onSpeechEnd?: () => void;
17
+ /** Called on transcript result */
18
+ onTranscript?: (text: string, isFinal: boolean) => void;
19
+ /** Called on error */
20
+ onError?: (error: Error) => void;
21
+ }
22
+ interface ASRClient {
23
+ /** Connect to ASR service */
24
+ connect(): Promise<void>;
25
+ /** Start recording from microphone */
26
+ startRecording(): Promise<void>;
27
+ /** Stop recording */
28
+ stopRecording(): void;
29
+ /** Close connection */
30
+ close(): void;
31
+ }
32
+ declare function createASRClient(config: ASRClientConfig): ASRClient;
33
+
34
+ export { type ASRClient, type ASRClientConfig, createASRClient };
package/dist/index.js ADDED
@@ -0,0 +1,136 @@
1
+ // src/asr-client.ts
2
+ function createASRClient(config) {
3
+ const {
4
+ url,
5
+ audioFormat = "pcm16",
6
+ sampleRate = 16e3,
7
+ onReady,
8
+ onSpeechStart,
9
+ onSpeechEnd,
10
+ onTranscript,
11
+ onError
12
+ } = config;
13
+ let ws = null;
14
+ let mediaStream = null;
15
+ let audioContext = null;
16
+ let processor = null;
17
+ async function connect() {
18
+ return new Promise((resolve, reject) => {
19
+ ws = new WebSocket(url);
20
+ ws.onopen = () => {
21
+ };
22
+ ws.onmessage = (event) => {
23
+ var _a;
24
+ const data = JSON.parse(event.data);
25
+ if (data.type === "session.created") {
26
+ onReady == null ? void 0 : onReady();
27
+ resolve();
28
+ }
29
+ if (data.type === "input_audio_buffer.speech_started") {
30
+ onSpeechStart == null ? void 0 : onSpeechStart();
31
+ }
32
+ if (data.type === "input_audio_buffer.speech_stopped") {
33
+ onSpeechEnd == null ? void 0 : onSpeechEnd();
34
+ }
35
+ if (data.type === "conversation.item.input_audio_transcription.text") {
36
+ onTranscript == null ? void 0 : onTranscript(data.text || "", false);
37
+ }
38
+ if (data.type === "conversation.item.input_audio_transcription.completed") {
39
+ onTranscript == null ? void 0 : onTranscript(data.text || data.transcript || "", true);
40
+ }
41
+ if (data.type === "error") {
42
+ const err = new Error(((_a = data.error) == null ? void 0 : _a.message) || "Unknown error");
43
+ onError == null ? void 0 : onError(err);
44
+ reject(err);
45
+ }
46
+ };
47
+ ws.onerror = () => {
48
+ const err = new Error("WebSocket connection error");
49
+ onError == null ? void 0 : onError(err);
50
+ reject(err);
51
+ };
52
+ ws.onclose = () => {
53
+ ws = null;
54
+ };
55
+ });
56
+ }
57
+ async function startRecording() {
58
+ if (typeof window === "undefined") {
59
+ throw new Error("Recording only supported in browser");
60
+ }
61
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
62
+ throw new Error("WebSocket not connected");
63
+ }
64
+ try {
65
+ mediaStream = await navigator.mediaDevices.getUserMedia({
66
+ audio: {
67
+ sampleRate,
68
+ channelCount: 1,
69
+ echoCancellation: true,
70
+ noiseSuppression: true
71
+ }
72
+ });
73
+ audioContext = new AudioContext({ sampleRate });
74
+ const source = audioContext.createMediaStreamSource(mediaStream);
75
+ processor = audioContext.createScriptProcessor(4096, 1, 1);
76
+ processor.onaudioprocess = (e) => {
77
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
78
+ const inputData = e.inputBuffer.getChannelData(0);
79
+ const pcm = new Int16Array(inputData.length);
80
+ for (let i = 0; i < inputData.length; i++) {
81
+ const s = Math.max(-1, Math.min(1, inputData[i]));
82
+ pcm[i] = s < 0 ? s * 32768 : s * 32767;
83
+ }
84
+ const bytes = new Uint8Array(pcm.buffer);
85
+ let binary = "";
86
+ for (let i = 0; i < bytes.length; i++) {
87
+ binary += String.fromCharCode(bytes[i]);
88
+ }
89
+ const base64 = btoa(binary);
90
+ ws.send(JSON.stringify({
91
+ type: "input_audio_buffer.append",
92
+ audio: base64
93
+ }));
94
+ };
95
+ source.connect(processor);
96
+ processor.connect(audioContext.destination);
97
+ } catch (err) {
98
+ onError == null ? void 0 : onError(err);
99
+ throw err;
100
+ }
101
+ }
102
+ function stopRecording() {
103
+ if (mediaStream) {
104
+ mediaStream.getTracks().forEach((track) => track.stop());
105
+ mediaStream = null;
106
+ }
107
+ if (processor) {
108
+ processor.disconnect();
109
+ processor = null;
110
+ }
111
+ if (audioContext) {
112
+ audioContext.close();
113
+ audioContext = null;
114
+ }
115
+ if (ws && ws.readyState === WebSocket.OPEN) {
116
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
117
+ }
118
+ }
119
+ function close() {
120
+ stopRecording();
121
+ if (ws) {
122
+ ws.close();
123
+ ws = null;
124
+ }
125
+ }
126
+ return {
127
+ connect,
128
+ startRecording,
129
+ stopRecording,
130
+ close
131
+ };
132
+ }
133
+ export {
134
+ createASRClient
135
+ };
136
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/asr-client.ts"],"sourcesContent":["/**\n * ASR Realtime WebSocket Client\n */\n\nexport interface ASRClientConfig {\n /** WebSocket endpoint URL */\n url: string;\n /** Audio format, default 'pcm16' */\n audioFormat?: 'pcm16' | 'g711a' | 'g711u';\n /** Sample rate, default 16000 */\n sampleRate?: number;\n /** Called when connection is ready */\n onReady?: () => void;\n /** Called when speech is detected */\n onSpeechStart?: () => void;\n /** Called when speech stops */\n onSpeechEnd?: () => void;\n /** Called on transcript result */\n onTranscript?: (text: string, isFinal: boolean) => void;\n /** Called on error */\n onError?: (error: Error) => void;\n}\n\nexport interface ASRClient {\n /** Connect to ASR service */\n connect(): Promise<void>;\n /** Start recording from microphone */\n startRecording(): Promise<void>;\n /** Stop recording */\n stopRecording(): void;\n /** Close connection */\n close(): void;\n}\n\nexport function createASRClient(config: ASRClientConfig): ASRClient {\n const {\n url,\n audioFormat = 'pcm16',\n sampleRate = 16000,\n onReady,\n onSpeechStart,\n onSpeechEnd,\n onTranscript,\n onError,\n } = config;\n\n let ws: WebSocket | null = null;\n let mediaStream: MediaStream | null = null;\n let audioContext: AudioContext | null = null;\n let processor: ScriptProcessorNode | null = null;\n\n async function connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n ws = new WebSocket(url);\n\n ws.onopen = () => {};\n\n ws.onmessage = (event) => {\n const data = JSON.parse(event.data);\n\n if (data.type === 'session.created') {\n onReady?.();\n resolve();\n }\n\n if (data.type === 'input_audio_buffer.speech_started') {\n onSpeechStart?.();\n }\n\n if (data.type === 'input_audio_buffer.speech_stopped') {\n onSpeechEnd?.();\n }\n\n if (data.type === 'conversation.item.input_audio_transcription.text') {\n onTranscript?.(data.text || '', false);\n }\n\n if (data.type === 'conversation.item.input_audio_transcription.completed') {\n onTranscript?.(data.text || data.transcript || '', true);\n }\n\n if (data.type === 'error') {\n const err = new Error(data.error?.message || 'Unknown error');\n onError?.(err);\n reject(err);\n }\n };\n\n ws.onerror = () => {\n const err = new Error('WebSocket connection error');\n onError?.(err);\n reject(err);\n };\n\n ws.onclose = () => {\n ws = null;\n };\n });\n }\n\n async function startRecording(): Promise<void> {\n if (typeof window === 'undefined') {\n throw new Error('Recording only supported in browser');\n }\n\n if (!ws || ws.readyState !== WebSocket.OPEN) {\n throw new Error('WebSocket not connected');\n }\n\n try {\n mediaStream = await navigator.mediaDevices.getUserMedia({\n audio: {\n sampleRate,\n channelCount: 1,\n echoCancellation: true,\n noiseSuppression: true,\n },\n });\n\n audioContext = new AudioContext({ sampleRate });\n const source = audioContext.createMediaStreamSource(mediaStream);\n processor = audioContext.createScriptProcessor(4096, 1, 1);\n\n processor.onaudioprocess = (e) => {\n if (!ws || ws.readyState !== WebSocket.OPEN) return;\n\n const inputData = e.inputBuffer.getChannelData(0);\n\n const pcm = new Int16Array(inputData.length);\n for (let i = 0; i < inputData.length; i++) {\n const s = Math.max(-1, Math.min(1, inputData[i]));\n pcm[i] = s < 0 ? s * 32768 : s * 32767;\n }\n\n const bytes = new Uint8Array(pcm.buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n const base64 = btoa(binary);\n\n ws.send(JSON.stringify({\n type: 'input_audio_buffer.append',\n audio: base64,\n }));\n };\n\n source.connect(processor);\n processor.connect(audioContext.destination);\n } catch (err) {\n onError?.(err as Error);\n throw err;\n }\n }\n\n function stopRecording() {\n if (mediaStream) {\n mediaStream.getTracks().forEach(track => track.stop());\n mediaStream = null;\n }\n\n if (processor) {\n processor.disconnect();\n processor = null;\n }\n\n if (audioContext) {\n audioContext.close();\n audioContext = null;\n }\n\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));\n }\n }\n\n function close() {\n stopRecording();\n if (ws) {\n ws.close();\n ws = null;\n }\n }\n\n return {\n connect,\n startRecording,\n stopRecording,\n close,\n };\n}\n"],"mappings":";AAkCO,SAAS,gBAAgB,QAAoC;AAClE,QAAM;AAAA,IACJ;AAAA,IACA,cAAc;AAAA,IACd,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,KAAuB;AAC3B,MAAI,cAAkC;AACtC,MAAI,eAAoC;AACxC,MAAI,YAAwC;AAE5C,iBAAe,UAAyB;AACtC,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,WAAK,IAAI,UAAU,GAAG;AAEtB,SAAG,SAAS,MAAM;AAAA,MAAC;AAEnB,SAAG,YAAY,CAAC,UAAU;AAzDhC;AA0DQ,cAAM,OAAO,KAAK,MAAM,MAAM,IAAI;AAElC,YAAI,KAAK,SAAS,mBAAmB;AACnC;AACA,kBAAQ;AAAA,QACV;AAEA,YAAI,KAAK,SAAS,qCAAqC;AACrD;AAAA,QACF;AAEA,YAAI,KAAK,SAAS,qCAAqC;AACrD;AAAA,QACF;AAEA,YAAI,KAAK,SAAS,oDAAoD;AAC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AAC,CAAC;AAChD,cAAI,CAAC,IAAI,IAAI,IAAI,IAAI,QAAQ,IAAI;AAAA,QACnC;AAEA,cAAM,QAAQ,IAAI,WAAW,IAAI,MAAM;AACvC,YAAI,SAAS;AACb,iBAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,oBAAU,OAAO,aAAa,MAAM,CAAC,CAAC;AAAA,QACxC;AACA,cAAM,SAAS,KAAK,MAAM;AAE1B,WAAG,KAAK,KAAK,UAAU;AAAA,UACrB,MAAM;AAAA,UACN,OAAO;AAAA,QACT,CAAC,CAAC;AAAA,MACJ;AAEA,aAAO,QAAQ,SAAS;AACxB,gBAAU,QAAQ,aAAa,WAAW;AAAA,IAC5C,SAAS,KAAK;AACZ,yCAAU;AACV,YAAM;AAAA,IACR;AAAA,EACF;AAEA,WAAS,gBAAgB;AACvB,QAAI,aAAa;AACf,kBAAY,UAAU,EAAE,QAAQ,WAAS,MAAM,KAAK,CAAC;AACrD,oBAAc;AAAA,IAChB;AAEA,QAAI,WAAW;AACb,gBAAU,WAAW;AACrB,kBAAY;AAAA,IACd;AAEA,QAAI,cAAc;AAChB,mBAAa,MAAM;AACnB,qBAAe;AAAA,IACjB;AAEA,QAAI,MAAM,GAAG,eAAe,UAAU,MAAM;AAC1C,SAAG,KAAK,KAAK,UAAU,EAAE,MAAM,4BAA4B,CAAC,CAAC;AAAA,IAC/D;AAAA,EACF;AAEA,WAAS,QAAQ;AACf,kBAAc;AACd,QAAI,IAAI;AACN,SAAG,MAAM;AACT,WAAK;AAAA,IACP;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@amaster.ai/asr-client",
3
+ "version": "1.0.0-beta.1",
4
+ "description": "Qwen ASR Realtime WebSocket client with microphone recording",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "keywords": [
21
+ "asr",
22
+ "speech-to-text",
23
+ "qwen",
24
+ "realtime",
25
+ "websocket",
26
+ "audio",
27
+ "speech-recognition"
28
+ ],
29
+ "author": "Amaster Team",
30
+ "license": "MIT",
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org/"
34
+ },
35
+ "devDependencies": {
36
+ "tsup": "^8.3.5",
37
+ "typescript": "~5.7.2"
38
+ },
39
+ "scripts": {
40
+ "build": "tsup",
41
+ "dev": "tsup --watch",
42
+ "clean": "rm -rf dist *.tsbuildinfo",
43
+ "type-check": "tsc --noEmit"
44
+ }
45
+ }