dsh-mobile-plugin 0.5.138 → 0.5.139
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/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/lib/impl.js +8 -5
- package/lib/mobile/permissions.js +10 -0
- package/lib/mobile/session-step.js +17 -11
- package/lib/mobile/voice/frames.js +198 -0
- package/lib/mobile/voice/gateway.js +746 -0
- package/lib/mobile/voice/lang.js +347 -0
- package/lib/mobile/voice/lexicon-store.js +189 -0
- package/lib/mobile/voice/lexicon.js +508 -0
- package/lib/mobile/voice/panel-api.js +88 -0
- package/lib/mobile/voice/postprocess.js +551 -0
- package/lib/mobile/voice/protocol.js +306 -0
- package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
- package/lib/mobile/voice/providers/cn/tencent.js +402 -0
- package/lib/mobile/voice/providers/cn/volc.js +328 -0
- package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
- package/lib/mobile/voice/providers/host.js +190 -0
- package/lib/mobile/voice/providers/intl/_common.js +346 -0
- package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
- package/lib/mobile/voice/providers/intl/azure.js +444 -0
- package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
- package/lib/mobile/voice/providers/intl/openai.js +389 -0
- package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
- package/lib/mobile/voice/providers/local/ondevice.js +129 -0
- package/lib/mobile/voice/providers/registry.js +277 -0
- package/lib/mobile/voice/routes.js +278 -0
- package/lib/mobile/voice/runtime.js +84 -0
- package/lib/mobile/voice/settings.js +206 -0
- package/lib/mobile/voice/stream.js +415 -0
- package/lib/mobile/voice/voice-provider.js +268 -0
- package/lib/panel/index.html +17 -17
- package/lib/routes/control-plane.js +19 -0
- package/lib/routes/mobile-api.js +33 -1
- package/lib/sidecar-facade-worker.cjs +1 -1
- package/package.json +13 -14
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// 腾讯云实时语音识别适配器:整段走一句话识别(TC3-HMAC-SHA256),流式走 asr v2 WebSocket(签名参与 HMAC)。
|
|
2
|
+
// 热词表要事先在控制台建好并拿 hotword_id,适配器不替用户建表,因此 hotwords 标 false。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const http = require('node:http');
|
|
7
|
+
const https = require('node:https');
|
|
8
|
+
const WebSocket = require('ws');
|
|
9
|
+
|
|
10
|
+
const DEFAULT_ENDPOINT = 'https://asr.tencentcloudapi.com';
|
|
11
|
+
const DEFAULT_STREAM_ENDPOINT = 'wss://asr.cloud.tencent.com/asr/v2';
|
|
12
|
+
const API_VERSION = '2019-06-14';
|
|
13
|
+
const API_SERVICE = 'asr';
|
|
14
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
15
|
+
const IDLE_TIMEOUT_MS = 15_000;
|
|
16
|
+
const FINISH_TIMEOUT_MS = 10_000;
|
|
17
|
+
const BATCH_TIMEOUT_MS = 30_000;
|
|
18
|
+
const MAX_SECONDS = 60;
|
|
19
|
+
const MAX_BYTES = 3 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
const ENGINE_MAP = { zh: '16k_zh', en: '16k_en', yue: '16k_yue', auto: '16k_zh' };
|
|
22
|
+
|
|
23
|
+
const configFields = [
|
|
24
|
+
{ key: 'secretId', label: 'SecretId', secret: false, required: true },
|
|
25
|
+
{ key: 'secretKey', label: 'SecretKey', secret: true, required: true },
|
|
26
|
+
{ key: 'appId', label: 'AppID(实时识别用)', secret: false, required: false },
|
|
27
|
+
{ key: 'region', label: '地域', secret: false, required: false, placeholder: 'ap-shanghai' },
|
|
28
|
+
{ key: 'engineModelType', label: '识别引擎(可选)', secret: false, required: false, placeholder: '16k_zh' },
|
|
29
|
+
{ key: 'endpoint', label: '一句话识别地址(可选)', secret: false, required: false, placeholder: DEFAULT_ENDPOINT },
|
|
30
|
+
{ key: 'streamEndpoint', label: '实时识别地址(可选)', secret: false, required: false, placeholder: DEFAULT_STREAM_ENDPOINT },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function voiceError(code, message, extra) {
|
|
34
|
+
const err = new Error(message);
|
|
35
|
+
err.code = code;
|
|
36
|
+
if (extra) Object.assign(err, extra);
|
|
37
|
+
return err;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sha256Hex(data) {
|
|
41
|
+
return crypto.createHash('sha256').update(data).digest('hex');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function hmac(key, data) {
|
|
45
|
+
return crypto.createHmac('sha256', key).update(data).digest();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// TC3-HMAC-SHA256:canonicalRequest → stringToSign → 派生签名密钥逐级 HMAC。
|
|
49
|
+
function tc3Authorization({ secretId, secretKey, host, payload, timestamp }) {
|
|
50
|
+
const date = new Date(timestamp * 1000).toISOString().slice(0, 10);
|
|
51
|
+
const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${host}\n`;
|
|
52
|
+
const signedHeaders = 'content-type;host';
|
|
53
|
+
const canonicalRequest = ['POST', '/', '', canonicalHeaders, signedHeaders, sha256Hex(payload)].join('\n');
|
|
54
|
+
const credentialScope = `${date}/${API_SERVICE}/tc3_request`;
|
|
55
|
+
const stringToSign = ['TC3-HMAC-SHA256', String(timestamp), credentialScope, sha256Hex(canonicalRequest)].join('\n');
|
|
56
|
+
const kDate = hmac(`TC3${secretKey}`, date);
|
|
57
|
+
const kService = hmac(kDate, API_SERVICE);
|
|
58
|
+
const kSigning = hmac(kService, 'tc3_request');
|
|
59
|
+
const signature = crypto.createHmac('sha256', kSigning).update(stringToSign).digest('hex');
|
|
60
|
+
return `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 实时识别签名:Base64(HmacSHA1(secretKey, host + path + ? + 参数按字典序拼接))。
|
|
64
|
+
function streamSignature(secretKey, hostAndPath, params) {
|
|
65
|
+
const query = Object.keys(params).sort().map((k) => `${k}=${params[k]}`).join('&');
|
|
66
|
+
return crypto.createHmac('sha1', secretKey).update(`${hostAndPath}?${query}`, 'utf8').digest('base64');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function mapErrorCode(code, message) {
|
|
70
|
+
const text = `${code} ${message || ''}`;
|
|
71
|
+
if (/AuthFailure|鉴权|签名|SecretId|未授权/i.test(text)) return 'voice-provider-unavailable';
|
|
72
|
+
if (/RequestLimitExceeded|LimitExceeded|限流|频率/i.test(text)) return 'voice-rate-limited';
|
|
73
|
+
if (/ResourceUnavailable|ResourceInsufficient|配额|欠费|余额/i.test(text)) return 'voice-quota';
|
|
74
|
+
if (/RequestTimeout|InternalError|超时/i.test(text)) return 'voice-timeout';
|
|
75
|
+
if (/InvalidParameter|Audio|音频|格式/i.test(text)) return 'voice-invalid-audio';
|
|
76
|
+
return 'voice-failed';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function mapWsCode(code, message) {
|
|
80
|
+
if (code === 4002 || code === 4001 || code === 4006) return 'voice-provider-unavailable';
|
|
81
|
+
if (code === 4004) return 'voice-rate-limited';
|
|
82
|
+
if (code === 4005) return 'voice-quota';
|
|
83
|
+
if (code === 4003) return 'voice-timeout';
|
|
84
|
+
return mapErrorCode(code, message);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function postJson(urlString, headers, body, { signal, timeoutMs }) {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
let url = null;
|
|
90
|
+
try { url = new URL(urlString); } catch { reject(voiceError('voice-provider-unavailable', '识别地址不可用')); return; }
|
|
91
|
+
const mod = url.protocol === 'https:' ? https : http;
|
|
92
|
+
const payload = Buffer.from(body, 'utf8');
|
|
93
|
+
const reqHeaders = { ...headers, 'content-length': payload.length };
|
|
94
|
+
let settled = false;
|
|
95
|
+
const finish = (fn, value) => {
|
|
96
|
+
if (settled) return;
|
|
97
|
+
settled = true;
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
100
|
+
fn(value);
|
|
101
|
+
};
|
|
102
|
+
const req = mod.request({
|
|
103
|
+
method: 'POST',
|
|
104
|
+
hostname: url.hostname,
|
|
105
|
+
port: url.port || undefined,
|
|
106
|
+
path: `${url.pathname}${url.search}`,
|
|
107
|
+
headers: reqHeaders,
|
|
108
|
+
}, (res) => {
|
|
109
|
+
const chunks = [];
|
|
110
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
111
|
+
res.on('end', () => finish(resolve, { status: res.statusCode || 0, body: Buffer.concat(chunks).toString('utf8') }));
|
|
112
|
+
});
|
|
113
|
+
req.on('error', () => finish(reject, voiceError('voice-provider-unavailable', '腾讯云连接失败')));
|
|
114
|
+
const timer = setTimeout(() => {
|
|
115
|
+
req.destroy();
|
|
116
|
+
finish(reject, voiceError('voice-timeout', '腾讯云识别超时'));
|
|
117
|
+
}, timeoutMs);
|
|
118
|
+
const onAbort = () => {
|
|
119
|
+
req.destroy();
|
|
120
|
+
finish(reject, voiceError('voice-failed', '已取消', { cancelled: true }));
|
|
121
|
+
};
|
|
122
|
+
if (signal) {
|
|
123
|
+
if (signal.aborted) { onAbort(); return; }
|
|
124
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
125
|
+
}
|
|
126
|
+
req.end(payload);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function configReady(config) {
|
|
131
|
+
return Boolean(
|
|
132
|
+
config
|
|
133
|
+
&& typeof config.secretId === 'string' && config.secretId.trim()
|
|
134
|
+
&& typeof config.secretKey === 'string' && config.secretKey.trim(),
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function pickEngine(config, hints) {
|
|
139
|
+
const langKey = String((hints && hints.lang) || 'auto').toLowerCase();
|
|
140
|
+
return String(config.engineModelType || '').trim() || ENGINE_MAP[langKey] || ENGINE_MAP.auto;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = {
|
|
144
|
+
id: 'tencent',
|
|
145
|
+
name: '腾讯云实时语音识别',
|
|
146
|
+
kind: 'cn',
|
|
147
|
+
batch: true,
|
|
148
|
+
streaming: true,
|
|
149
|
+
languages: ['zh', 'en', 'yue', 'auto'],
|
|
150
|
+
hotwords: false,
|
|
151
|
+
maxSeconds: MAX_SECONDS,
|
|
152
|
+
maxBytes: MAX_BYTES,
|
|
153
|
+
configFields,
|
|
154
|
+
|
|
155
|
+
ready(config) {
|
|
156
|
+
return configReady(config);
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
async transcribe({ config, audio, hints, signal } = {}) {
|
|
160
|
+
const cfg = config && typeof config === 'object' ? config : {};
|
|
161
|
+
if (!configReady(cfg)) throw voiceError('voice-provider-unavailable', '腾讯云未配置 SecretId / SecretKey');
|
|
162
|
+
if (!audio || !audio.length) throw voiceError('voice-invalid-audio', '音频为空');
|
|
163
|
+
if (audio.length > MAX_BYTES) throw voiceError('voice-too-large', '音频超过一句话识别上限');
|
|
164
|
+
if (signal && signal.aborted) throw voiceError('voice-failed', '已取消', { cancelled: true });
|
|
165
|
+
|
|
166
|
+
const endpoint = String(cfg.endpoint || '').trim() || DEFAULT_ENDPOINT;
|
|
167
|
+
let host = '';
|
|
168
|
+
try { host = new URL(endpoint).host; } catch { throw voiceError('voice-provider-unavailable', '腾讯云一句话识别地址不可用'); }
|
|
169
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
170
|
+
const body = JSON.stringify({
|
|
171
|
+
EngSerViceType: pickEngine(cfg, hints),
|
|
172
|
+
SourceType: 1,
|
|
173
|
+
VoiceFormat: 'wav',
|
|
174
|
+
Data: audio.toString('base64'),
|
|
175
|
+
WordInfo: 0,
|
|
176
|
+
});
|
|
177
|
+
const headers = {
|
|
178
|
+
'content-type': 'application/json; charset=utf-8',
|
|
179
|
+
host,
|
|
180
|
+
authorization: tc3Authorization({ secretId: cfg.secretId.trim(), secretKey: cfg.secretKey.trim(), host, payload: body, timestamp }),
|
|
181
|
+
'x-tc-action': 'SentenceRecognition',
|
|
182
|
+
'x-tc-version': API_VERSION,
|
|
183
|
+
'x-tc-timestamp': String(timestamp),
|
|
184
|
+
'x-tc-region': String(cfg.region || '').trim() || 'ap-shanghai',
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const res = await postJson(endpoint, headers, body, { signal, timeoutMs: BATCH_TIMEOUT_MS });
|
|
188
|
+
let data = null;
|
|
189
|
+
try { data = JSON.parse(res.body); } catch { data = null; }
|
|
190
|
+
const response = data && data.Response ? data.Response : null;
|
|
191
|
+
if (!response) throw voiceError('voice-provider-unavailable', '腾讯云返回无法解析');
|
|
192
|
+
if (response.Error) {
|
|
193
|
+
const code = response.Error.Code || '';
|
|
194
|
+
throw voiceError(mapErrorCode(code, response.Error.Message), `腾讯云识别失败 ${code}`);
|
|
195
|
+
}
|
|
196
|
+
if (typeof response.Result !== 'string') throw voiceError('voice-failed', '腾讯云返回缺少识别结果');
|
|
197
|
+
const langKey = String((hints && hints.lang) || '').toLowerCase();
|
|
198
|
+
return {
|
|
199
|
+
text: response.Result,
|
|
200
|
+
lang: langKey && langKey !== 'auto' && ENGINE_MAP[langKey] ? langKey : undefined,
|
|
201
|
+
};
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
|
|
205
|
+
const cfg = config && typeof config === 'object' ? config : {};
|
|
206
|
+
const h = hints && typeof hints === 'object' ? hints : {};
|
|
207
|
+
const emitPartial = typeof onPartial === 'function' ? onPartial : () => {};
|
|
208
|
+
const emitFinal = typeof onFinal === 'function' ? onFinal : () => {};
|
|
209
|
+
const emitError = typeof onError === 'function' ? onError : () => {};
|
|
210
|
+
const noop = { push() {}, finish() {}, cancel() {} };
|
|
211
|
+
|
|
212
|
+
if (!configReady(cfg)) {
|
|
213
|
+
queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '腾讯云未配置 SecretId / SecretKey')));
|
|
214
|
+
return noop;
|
|
215
|
+
}
|
|
216
|
+
if (signal && signal.aborted) {
|
|
217
|
+
queueMicrotask(() => emitError(voiceError('voice-failed', '已取消', { cancelled: true })));
|
|
218
|
+
return noop;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const secretId = cfg.secretId.trim();
|
|
222
|
+
const secretKey = cfg.secretKey.trim();
|
|
223
|
+
const endpoint = String(cfg.streamEndpoint || '').trim() || DEFAULT_STREAM_ENDPOINT;
|
|
224
|
+
const appId = String(cfg.appId || '').trim();
|
|
225
|
+
if (!appId) {
|
|
226
|
+
queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '腾讯云实时识别需要 AppID')));
|
|
227
|
+
return noop;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
let parsedEndpoint = null;
|
|
231
|
+
try { parsedEndpoint = new URL(endpoint); } catch {
|
|
232
|
+
queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '腾讯云实时识别地址不可用')));
|
|
233
|
+
return noop;
|
|
234
|
+
}
|
|
235
|
+
const path = `${parsedEndpoint.pathname.replace(/\/$/, '')}/${appId}`;
|
|
236
|
+
const hostAndPath = `${parsedEndpoint.hostname}${path}`;
|
|
237
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
238
|
+
const params = {
|
|
239
|
+
engine_model_type: pickEngine(cfg, h),
|
|
240
|
+
expire_time: String(timestamp + 86_400),
|
|
241
|
+
needvad: '1',
|
|
242
|
+
nonce: String(crypto.randomInt(1_000_000_000, 2_147_483_647)),
|
|
243
|
+
secretid: secretId,
|
|
244
|
+
timestamp: String(timestamp),
|
|
245
|
+
voice_format: '1',
|
|
246
|
+
};
|
|
247
|
+
params.signature = streamSignature(secretKey, hostAndPath, params);
|
|
248
|
+
const query = Object.keys(params).sort().map((k) => `${k}=${encodeURIComponent(params[k])}`).join('&');
|
|
249
|
+
const url = `${parsedEndpoint.protocol}//${parsedEndpoint.host}${path}?${query}`;
|
|
250
|
+
|
|
251
|
+
let socket = null;
|
|
252
|
+
let opened = false;
|
|
253
|
+
let settled = false;
|
|
254
|
+
let finishRequested = false;
|
|
255
|
+
let finalText = '';
|
|
256
|
+
const pendingAudio = [];
|
|
257
|
+
let idleTimer = null;
|
|
258
|
+
let finishTimer = null;
|
|
259
|
+
|
|
260
|
+
const connectTimer = setTimeout(() => fail(voiceError('voice-timeout', '连接腾讯云超时')), CONNECT_TIMEOUT_MS);
|
|
261
|
+
|
|
262
|
+
function clearTimers() {
|
|
263
|
+
clearTimeout(connectTimer);
|
|
264
|
+
clearTimeout(idleTimer);
|
|
265
|
+
clearTimeout(finishTimer);
|
|
266
|
+
idleTimer = null;
|
|
267
|
+
finishTimer = null;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function closeSocket() {
|
|
271
|
+
if (!socket) return;
|
|
272
|
+
try { socket.removeAllListeners(); } catch {}
|
|
273
|
+
try { socket.close(); } catch {}
|
|
274
|
+
try { socket.terminate(); } catch {}
|
|
275
|
+
socket = null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function detachAbort() {
|
|
279
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function fail(err) {
|
|
283
|
+
if (settled) return;
|
|
284
|
+
settled = true;
|
|
285
|
+
clearTimers();
|
|
286
|
+
detachAbort();
|
|
287
|
+
closeSocket();
|
|
288
|
+
emitError(err);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function succeed() {
|
|
292
|
+
if (settled) return;
|
|
293
|
+
settled = true;
|
|
294
|
+
clearTimers();
|
|
295
|
+
detachAbort();
|
|
296
|
+
closeSocket();
|
|
297
|
+
const langKey = String(h.lang || '').toLowerCase();
|
|
298
|
+
const langOut = langKey && langKey !== 'auto' ? langKey : undefined;
|
|
299
|
+
emitFinal(finalText.trim(), langOut ? { lang: langOut } : undefined);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function armIdle() {
|
|
303
|
+
clearTimeout(idleTimer);
|
|
304
|
+
idleTimer = setTimeout(() => fail(voiceError('voice-timeout', '腾讯云长时间没有返回结果')), IDLE_TIMEOUT_MS);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function onAbort() {
|
|
308
|
+
if (settled) return;
|
|
309
|
+
settled = true;
|
|
310
|
+
clearTimers();
|
|
311
|
+
closeSocket();
|
|
312
|
+
emitError(voiceError('voice-failed', '已取消', { cancelled: true }));
|
|
313
|
+
}
|
|
314
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
|
315
|
+
|
|
316
|
+
function sendBinary(pcm) {
|
|
317
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) return;
|
|
318
|
+
socket.send(pcm);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function handleMessage(raw) {
|
|
322
|
+
let msg = null;
|
|
323
|
+
try { msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString('utf8')); } catch { return; }
|
|
324
|
+
if (!msg || typeof msg !== 'object') return;
|
|
325
|
+
if (msg.code && msg.code !== 0) {
|
|
326
|
+
fail(voiceError(mapWsCode(msg.code, msg.message), `腾讯云实时识别失败 ${msg.code}`));
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const result = msg.result && typeof msg.result === 'object' ? msg.result : null;
|
|
330
|
+
if (result && typeof result.voice_text_str === 'string' && result.voice_text_str) {
|
|
331
|
+
finalText += result.voice_text_str;
|
|
332
|
+
try { emitPartial(finalText); } catch {}
|
|
333
|
+
}
|
|
334
|
+
if (msg.final === 1 || msg.final === true) {
|
|
335
|
+
succeed();
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
armIdle();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
try {
|
|
342
|
+
socket = new WebSocket(url, { handshakeTimeout: CONNECT_TIMEOUT_MS });
|
|
343
|
+
} catch {
|
|
344
|
+
clearTimers();
|
|
345
|
+
detachAbort();
|
|
346
|
+
queueMicrotask(() => fail(voiceError('voice-provider-unavailable', '腾讯云实时识别地址不可用')));
|
|
347
|
+
return noop;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
socket.on('open', () => {
|
|
351
|
+
opened = true;
|
|
352
|
+
clearTimeout(connectTimer);
|
|
353
|
+
for (const pcm of pendingAudio) sendBinary(pcm);
|
|
354
|
+
pendingAudio.length = 0;
|
|
355
|
+
if (finishRequested) socket.send(JSON.stringify({ type: 'end' }));
|
|
356
|
+
armIdle();
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
socket.on('message', (data) => {
|
|
360
|
+
if (settled) return;
|
|
361
|
+
armIdle();
|
|
362
|
+
handleMessage(data);
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
socket.on('error', () => {
|
|
366
|
+
fail(voiceError('voice-provider-unavailable', '腾讯云实时识别连接失败'));
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
socket.on('close', () => {
|
|
370
|
+
if (settled) return;
|
|
371
|
+
if (finishRequested) succeed();
|
|
372
|
+
else fail(voiceError('voice-provider-unavailable', '腾讯云实时识别连接被关闭'));
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
return {
|
|
376
|
+
push(pcmBuf, _seq) {
|
|
377
|
+
if (settled || !pcmBuf || !pcmBuf.length) return;
|
|
378
|
+
const pcm = Buffer.isBuffer(pcmBuf) ? pcmBuf : Buffer.from(pcmBuf);
|
|
379
|
+
if (!opened) {
|
|
380
|
+
pendingAudio.push(pcm);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
sendBinary(pcm);
|
|
384
|
+
},
|
|
385
|
+
finish() {
|
|
386
|
+
if (settled || finishRequested) return;
|
|
387
|
+
finishRequested = true;
|
|
388
|
+
if (!opened) return;
|
|
389
|
+
if (socket && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'end' }));
|
|
390
|
+
clearTimeout(idleTimer);
|
|
391
|
+
finishTimer = setTimeout(() => succeed(), FINISH_TIMEOUT_MS);
|
|
392
|
+
},
|
|
393
|
+
cancel() {
|
|
394
|
+
if (settled) return;
|
|
395
|
+
settled = true;
|
|
396
|
+
clearTimers();
|
|
397
|
+
detachAbort();
|
|
398
|
+
closeSocket();
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
},
|
|
402
|
+
};
|