jbc-dssi 1.1.156 → 1.1.157

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.
Files changed (2) hide show
  1. package/lib/edge-tts.js +114 -29
  2. package/package.json +1 -2
package/lib/edge-tts.js CHANGED
@@ -1,4 +1,8 @@
1
- import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
1
+ import WebSocket from 'ws';
2
+ import { randomUUID } from 'node:crypto';
3
+ import SecMsGec from '../vendor/SecMsGec.cjs';
4
+
5
+ const { hashSecMsGecV2 } = SecMsGec;
2
6
 
3
7
  export const EDGE_VOICES = [
4
8
  { id: 'zh-CN-XiaoxiaoNeural', name: '晓晓', gender: '女声', note: '温暖自然' },
@@ -20,62 +24,143 @@ export const EDGE_VOICES = [
20
24
 
21
25
  export const DEFAULT_EDGE_VOICE = 'zh-CN-XiaoxiaoNeural';
22
26
 
23
- const MP3 = OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3;
27
+ const TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';
28
+ const BASE = 'wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1';
29
+ const OUTPUT = 'audio-24khz-48kbitrate-mono-mp3';
30
+ const VOICE_LANG = 'zh-CN';
24
31
 
25
32
  function voiceOf(id) {
26
33
  return EDGE_VOICES.some((v) => v.id === id) ? id : DEFAULT_EDGE_VOICE;
27
34
  }
28
35
 
36
+ function escapeXml(text) {
37
+ return String(text)
38
+ .replace(/&/g, '&')
39
+ .replace(/</g, '&lt;')
40
+ .replace(/>/g, '&gt;')
41
+ .replace(/"/g, '&quot;')
42
+ .replace(/'/g, '&apos;');
43
+ }
44
+
45
+ function stamp() {
46
+ return new Date().toISOString();
47
+ }
48
+
49
+ function ssml(text, voice) {
50
+ return `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='${VOICE_LANG}'>` +
51
+ `<voice name='${voice}'><prosody rate='0%' pitch='0Hz' volume='0%'>${escapeXml(text)}</prosody></voice></speak>`;
52
+ }
53
+
54
+ function configMessage() {
55
+ const body = JSON.stringify({
56
+ context: {
57
+ synthesis: {
58
+ audio: {
59
+ metadataoptions: { sentenceBoundaryEnabled: false, wordBoundaryEnabled: false },
60
+ outputFormat: OUTPUT,
61
+ },
62
+ },
63
+ },
64
+ });
65
+ return `X-Timestamp:${stamp()}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n${body}`;
66
+ }
67
+
68
+ function ssmlMessage(text, voice, requestId) {
69
+ return `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${stamp()}\r\nPath:ssml\r\n\r\n${ssml(text, voice)}`;
70
+ }
71
+
29
72
  export function createEdgeTts({ log }) {
30
73
  const sessions = new Map();
31
74
 
32
75
  async function synthesize({ id, text, voice, onChunk }) {
33
76
  const body = String(text ?? '');
34
77
  if (body.trim() === '') return { ok: false, message: '没有可朗读的文本' };
35
- const tts = new MsEdgeTTS({ connectionTimeoutMs: 10_000, synthesisTimeoutMs: 120_000 });
78
+ const requestId = randomUUID();
79
+ const ticks = Math.floor(Date.now() / 1000) + 11644473600;
80
+ const rounded = ticks - (ticks % 300);
81
+ let secMsGec = '';
82
+ try {
83
+ secMsGec = await hashSecMsGecV2(`${rounded * 10000000}${TOKEN}`);
84
+ } catch (err) {
85
+ log?.(`[edge-tts] GEC 计算失败: ${err?.message ?? err}`);
86
+ }
87
+ const url = `${BASE}?TrustedClientToken=${TOKEN}&Sec-MS-GEC=${secMsGec}&Sec-MS-GEC-Version=2-143.0.3650.96&ConnectionId=${requestId}`;
88
+ let ws;
36
89
  try {
37
- await tts.setMetadata(voiceOf(voice), MP3);
90
+ ws = new WebSocket(url, {
91
+ headers: {
92
+ Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',
93
+ Pragma: 'no-cache',
94
+ 'Cache-Control': 'no-cache',
95
+ 'User-Agent':
96
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',
97
+ },
98
+ });
38
99
  } catch (err) {
39
- log?.(`[edge-tts] 元数据失败: ${err?.message ?? err}`);
40
- return { ok: false, message: '微软语音服务连接失败' };
100
+ return { ok: false, message: `语音服务连接失败:${err?.message ?? err}` };
41
101
  }
102
+
42
103
  return await new Promise((resolve) => {
104
+ let settled = false;
43
105
  let seq = 0;
44
106
  let bytes = 0;
45
- let settled = false;
46
- const { audioStream } = tts.toStream(body);
47
- sessions.set(id, { close: () => audioStream.destroy() });
48
- audioStream.on('data', (data) => {
49
- if (settled) return;
50
- const chunk = Buffer.from(data);
51
- bytes += chunk.length;
52
- onChunk?.({ id, seq: seq++, data: chunk.toString('base64'), codec: 'mp3' });
53
- });
54
- audioStream.on('close', () => {
107
+ const timer = setTimeout(() => finish({ ok: false, message: '语音合成超时' }), 120_000);
108
+
109
+ function finish(result) {
55
110
  if (settled) return;
56
111
  settled = true;
112
+ clearTimeout(timer);
57
113
  sessions.delete(id);
58
- resolve(bytes > 0 ? { ok: true, bytes } : { ok: false, message: '微软语音没有返回音频' });
114
+ try {
115
+ ws.close();
116
+ } catch {
117
+ /* 已关闭 */
118
+ }
119
+ resolve(result);
120
+ }
121
+
122
+ sessions.set(id, { close: () => finish({ ok: false, message: '已取消' }) });
123
+
124
+ ws.on('open', () => {
125
+ try {
126
+ ws.send(configMessage());
127
+ ws.send(ssmlMessage(body, voiceOf(voice), requestId));
128
+ } catch (err) {
129
+ finish({ ok: false, message: `语音发送失败:${err?.message ?? err}` });
130
+ }
59
131
  });
60
- audioStream.on('error', (err) => {
61
- if (settled) return;
62
- settled = true;
63
- sessions.delete(id);
64
- log?.(`[edge-tts] 合成失败: ${err?.message ?? err}`);
65
- resolve({ ok: false, message: '微软语音合成失败' });
132
+
133
+ ws.on('message', (data, isBinary) => {
134
+ if (!isBinary) {
135
+ const textFrame = data.toString('utf8');
136
+ if (textFrame.includes('Path:turn.end')) {
137
+ finish(bytes > 0 ? { ok: true, bytes } : { ok: false, message: '语音服务没有返回音频' });
138
+ }
139
+ return;
140
+ }
141
+ const buffer = Buffer.from(data);
142
+ const headerLength = buffer.readUInt16BE(0);
143
+ const header = buffer.subarray(2, 2 + headerLength).toString('utf8');
144
+ if (!header.includes('Path:audio')) return;
145
+ const audio = buffer.subarray(2 + headerLength);
146
+ if (audio.length === 0) return;
147
+ bytes += audio.length;
148
+ onChunk?.({ id, seq: seq++, data: audio.toString('base64'), codec: 'mp3' });
149
+ });
150
+
151
+ ws.on('error', (err) => {
152
+ log?.(`[edge-tts] 连接异常: ${err?.message ?? err}`);
153
+ finish({ ok: false, message: '微软语音连接失败' });
66
154
  });
155
+
156
+ ws.on('close', () => finish({ ok: false, message: '微软语音连接中断' }));
67
157
  });
68
158
  }
69
159
 
70
160
  function stop(id) {
71
161
  const session = sessions.get(id);
72
162
  if (!session) return;
73
- sessions.delete(id);
74
- try {
75
- session.close();
76
- } catch {
77
- /* 已关闭 */
78
- }
163
+ session.close();
79
164
  }
80
165
 
81
166
  function stopAll() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jbc-dssi",
3
- "version": "1.1.156",
3
+ "version": "1.1.157",
4
4
  "type": "module",
5
5
  "description": "鲸聊 - 不只是手机遥控操作电脑,而是将电脑级的Agent能力装进手机",
6
6
  "keywords": [
@@ -52,7 +52,6 @@
52
52
  "prepack": "node scripts/build-vendor.mjs"
53
53
  },
54
54
  "dependencies": {
55
- "msedge-tts": "^2.1.1",
56
55
  "ws": "^8.18.0"
57
56
  }
58
57
  }