-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
618 lines (547 loc) · 24.3 KB
/
server.js
File metadata and controls
618 lines (547 loc) · 24.3 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
/**
* ToMic - Server
*
* 核心服务端代码,负责:
* 1. 启动 HTTPS 服务和 WebSocket 服务
* 2. 接收客户端音频流
* 3. 使用 FFmpeg 进行音频转码 (WebM -> PCM)
* 4. 通过 SoX 将音频输出到虚拟声卡 (BlackHole/VB-CABLE)
*
* @author Your Name
* @license MIT
*/
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const selfsigned = require('selfsigned');
const { Server } = require('socket.io');
const { spawn } = require('child_process');
const { spawnSync } = require('child_process');
// const Speaker = require('speaker'); // Removed dependency
const ffmpeg = require('fluent-ffmpeg');
const { PassThrough } = require('stream');
const os = require('os');
// 平台检测
const IS_MAC = os.platform() === 'darwin';
const IS_WIN = os.platform() === 'win32';
// 路径配置
const isPkg = typeof process.pkg !== 'undefined';
const BASE_DIR = isPkg ? path.dirname(process.execPath) : __dirname;
// 统一 Native 目录查找逻辑
// Windows: native/windows-listener
// macOS: native
const NATIVE_DIR = path.join(BASE_DIR, 'native');
const LOCAL_WIN_LISTENER_DIR = path.join(NATIVE_DIR, 'windows-listener');
// Windows 路径
let WIN_SOX_PATH = path.join(LOCAL_WIN_LISTENER_DIR, 'sox.exe');
let WIN_FFMPEG_PATH = path.join(LOCAL_WIN_LISTENER_DIR, 'ffmpeg.exe');
// 如果是打包环境,优先查找扁平目录 (native/sox.exe, native/ffmpeg.exe)
if (IS_WIN && isPkg) {
const pkgSoxPath = path.join(NATIVE_DIR, 'sox.exe');
if (fs.existsSync(pkgSoxPath)) {
WIN_SOX_PATH = pkgSoxPath;
}
const pkgFfmpegPath = path.join(NATIVE_DIR, 'ffmpeg.exe');
if (fs.existsSync(pkgFfmpegPath)) {
WIN_FFMPEG_PATH = pkgFfmpegPath;
}
}
// macOS 路径 (独立打包后位于 native/ffmpeg, native/sox)
const MAC_SOX_PATH = path.join(NATIVE_DIR, 'sox');
const MAC_FFMPEG_PATH = path.join(NATIVE_DIR, 'ffmpeg');
// 二进制文件路径和状态
let soxPath = 'sox'; // 默认系统命令
let ffmpegPath = 'ffmpeg'; // 默认系统命令
let hasSox = false;
let hasFfmpeg = false;
let soxUseDefaultDevice = false; // Windows 下 sox 需要 -d 参数
const MAC_OUTPUT_DEVICE_CANDIDATES = [
'BlackHole 2ch',
'BlackHole 16ch',
'BlackHole 64ch'
];
let macOutputDevice = process.env.TOMIC_OUTPUT_DEVICE || '';
function collectBlackHoleNames(value, names = new Set()) {
if (!value) return names;
if (Array.isArray(value)) {
for (const item of value) collectBlackHoleNames(item, names);
return names;
}
if (typeof value === 'object') {
for (const [key, item] of Object.entries(value)) {
if (/name/i.test(key) && typeof item === 'string' && /blackhole/i.test(item)) {
names.add(item.trim());
}
collectBlackHoleNames(item, names);
}
return names;
}
if (typeof value === 'string' && /blackhole/i.test(value)) {
names.add(value.trim());
}
return names;
}
function parseBlackHoleNamesFromSystemProfilerText(text) {
const names = new Set();
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (!/blackhole/i.test(trimmed)) continue;
const match = trimmed.match(/^([^:]+):\s*$/);
if (match) {
names.add(match[1].trim());
continue;
}
names.add(trimmed.replace(/:$/, '').trim());
}
return [...names];
}
function detectMacOutputDevice() {
if (!IS_MAC) return '';
if (macOutputDevice) {
console.log(`【系统初始化】使用环境变量指定的输出设备: ${macOutputDevice}`);
return macOutputDevice;
}
const discoveredNames = new Set();
try {
const profilerJson = spawnSync('system_profiler', ['-json', 'SPAudioDataType'], { encoding: 'utf8' });
if (profilerJson.status === 0 && profilerJson.stdout) {
const parsed = JSON.parse(profilerJson.stdout);
collectBlackHoleNames(parsed, discoveredNames);
}
} catch (e) {
// 忽略并继续尝试文本解析
}
if (discoveredNames.size === 0) {
try {
const profilerText = spawnSync('system_profiler', ['SPAudioDataType'], { encoding: 'utf8' });
if (profilerText.status === 0 && profilerText.stdout) {
for (const name of parseBlackHoleNamesFromSystemProfilerText(profilerText.stdout)) {
discoveredNames.add(name);
}
}
} catch (e) {
// 忽略并走候选名回退
}
}
for (const candidate of MAC_OUTPUT_DEVICE_CANDIDATES) {
const matched = [...discoveredNames].find((name) => name.toLowerCase() === candidate.toLowerCase());
if (matched) {
macOutputDevice = matched;
console.log(`【系统初始化】自动探测到 BlackHole 输出设备: ${macOutputDevice}`);
return macOutputDevice;
}
}
const firstDetected = [...discoveredNames][0];
if (firstDetected) {
macOutputDevice = firstDetected;
console.log(`【系统初始化】自动探测到虚拟输出设备: ${macOutputDevice}`);
return macOutputDevice;
}
macOutputDevice = MAC_OUTPUT_DEVICE_CANDIDATES[0];
console.log(`【系统初始化】未能自动探测 BlackHole,回退使用默认设备名: ${macOutputDevice}`);
return macOutputDevice;
}
// 1. 检测 FFmpeg
if (IS_WIN && fs.existsSync(WIN_FFMPEG_PATH)) {
ffmpegPath = WIN_FFMPEG_PATH;
console.log(`【系统初始化】检测到本地 FFmpeg: ${ffmpegPath}`);
} else if (IS_MAC && fs.existsSync(MAC_FFMPEG_PATH)) {
ffmpegPath = MAC_FFMPEG_PATH;
console.log(`【系统初始化】检测到本地 FFmpeg: ${ffmpegPath}`);
}
if (IS_MAC) {
detectMacOutputDevice();
}
// 设置 ffmpeg 路径
try {
ffmpeg.setFfmpegPath(ffmpegPath);
hasFfmpeg = true;
} catch (e) {
console.error('【系统初始化】FFmpeg 配置异常:', e.message);
hasFfmpeg = false;
}
// 2. 检测 SoX
if (IS_WIN) {
if (fs.existsSync(WIN_SOX_PATH)) {
soxPath = WIN_SOX_PATH;
hasSox = true;
soxUseDefaultDevice = true;
console.log(`【系统初始化】检测到本地 SoX: ${soxPath}`);
} else {
// 尝试系统路径
const checkSox = require('child_process').spawnSync('sox', ['--version']);
if (checkSox.status === 0) {
hasSox = true;
soxUseDefaultDevice = true;
console.log('【系统初始化】检测到系统 SoX');
}
}
} else {
// macOS / Linux
if (IS_MAC && fs.existsSync(MAC_SOX_PATH)) {
soxPath = MAC_SOX_PATH;
hasSox = true;
console.log(`【系统初始化】检测到本地 SoX: ${soxPath}`);
} else {
const checkSox = require('child_process').spawnSync('sox', ['--version']);
if (checkSox.status === 0) {
hasSox = true;
console.log('【系统初始化】检测到 SoX 音频工具');
}
}
}
if (hasSox) {
console.log('【系统初始化】SoX 就绪,将启用定向音频路由 (BlackHole/VB-CABLE)');
} else {
console.log('【系统初始化】未检测到 SoX,将使用默认音频输出设备 (Speaker)');
if (IS_MAC) {
console.log('【建议】运行 "brew install sox" 以支持定向输出到 BlackHole');
} else if (IS_WIN) {
console.log('【建议】请确保 native/windows-listener/sox.exe 存在');
console.log('【下载地址】https://github.com/turbulentie/sox-dsd-win/blob/main/sox-dsd-win32_64.zip');
}
}
// 检查 FFmpeg 是否可用,如果不可用给提示
// 注意:fluent-ffmpeg 只有在实际运行命令时才会报错,所以这里最好预检一下
// 但上面已经设置了路径,我们相信用户
if (!fs.existsSync(ffmpegPath) && IS_WIN) {
console.log('【警告】未找到 ffmpeg.exe。');
console.log('【建议】请下载 ffmpeg.exe 并放置于 native/windows-listener/ffmpeg.exe');
console.log('【下载地址】https://github.com/GyanD/codexffmpeg/releases');
}
// 配置
const PORT = 23336;
// 证书目录必须在可执行文件外部(因为 pkg 内部只读)
const CERT_DIR = path.join(BASE_DIR, 'certs');
const OUTPUT_HINT = IS_MAC ? `
【输出设备提示】
请将系统“声音->输出设备”切换为虚拟设备:
- macOS 请选择 BlackHole 2ch(推荐“无监听”版本避免本机扬声器播放)
- Windows 请选择 VB-CABLE(CABLE Input)
如果输出仍为内置扬声器,将产生本机回放与回声。
` : IS_WIN ? `
【输出设备提示】
请将系统“声音->输出设备”切换为虚拟设备:
- Windows 请选择 VB-CABLE(CABLE Input)
如果输出仍为内置扬声器,将产生本机回放与回声。
` : '';
// 确保证书目录存在
if (!fs.existsSync(CERT_DIR)) {
try {
fs.mkdirSync(CERT_DIR, { recursive: true });
} catch (e) {
console.error(`【系统初始化】无法创建证书目录: ${CERT_DIR}`, e);
}
}
// 获取或生成证书
async function getCertificates() {
const keyPath = path.join(CERT_DIR, 'private.key');
const certPath = path.join(CERT_DIR, 'certificate.crt');
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
console.log('【系统初始化】检测到现有证书,正在加载...');
return {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
}
console.log('【系统初始化】正在生成新的自签名证书 (这可能需要几秒钟)...');
const attrs = [{ name: 'commonName', value: 'localhost' }];
// selfsigned.generate 在新版本中返回 Promise
const pems = await selfsigned.generate(attrs, { days: 365 });
fs.writeFileSync(keyPath, pems.private);
fs.writeFileSync(certPath, pems.cert);
console.log('【系统初始化】证书生成完毕');
return {
key: pems.private,
cert: pems.cert
};
}
// 主初始化流程
async function startServer() {
try {
const app = express();
const options = await getCertificates();
const server = https.createServer(options, app);
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
},
serveClient: false // 统一禁用自动 serve,改用静态文件/手动路由
});
app.use(express.json());
// public 目录在 pkg 中会被自动打包到 snapshot 中,__dirname 可用
app.use(express.static(path.join(BASE_DIR, 'public')));
// 开发环境:手动路由 lib/socket.io.js 到 node_modules
if (!isPkg) {
app.get('/lib/socket.io.js', (req, res) => {
// 尝试查找 node_modules 中的 socket.io 客户端文件
try {
const socketIoBase = path.dirname(require.resolve('socket.io/package.json'));
res.sendFile(path.join(socketIoBase, 'client-dist', 'socket.io.js'));
} catch (e) {
res.status(404).send('socket.io client file not found');
}
});
app.get('/lib/socket.io.js.map', (req, res) => {
try {
const socketIoBase = path.dirname(require.resolve('socket.io/package.json'));
res.sendFile(path.join(socketIoBase, 'client-dist', 'socket.io.js.map'));
} catch (e) {
res.status(404).send('map file not found');
}
});
}
let demandState = false;
app.post('/api/mic/start', (req, res) => {
demandState = true;
io.emit('server-start');
console.log('【待机控制】已向所有客户端广播:开始拾音');
res.json({ ok: true });
});
app.post('/api/mic/stop', (req, res) => {
demandState = false;
io.emit('server-stop');
console.log('【待机控制】已向所有客户端广播:停止拾音');
res.json({ ok: true });
});
io.on('connection', (socket) => {
console.log(`【连接管理】客户端已连接 ID: ${socket.id}`);
// 新连接同步期望状态
if (demandState) {
socket.emit('server-start');
} else {
socket.emit('server-stop');
}
// 每个连接创建一个音频处理管道
let audioStream = new PassThrough();
let ffmpegCommand = null;
// let speaker = null;
let soxProcess = null;
let desiredStreaming = false;
let pipelineState = 'idle';
// 初始化 FFmpeg 转换流 (WebM -> PCM -> Speaker/SoX)
function startAudioPipeline() {
if (ffmpegCommand) return;
pipelineState = 'running';
console.log(`【音频管道】正在为客户端 ${socket.id} 初始化音频管道...`);
let outputStream;
if (hasSox) {
// 使用 SoX 定向输出
// macOS: play -t raw ... (play 实际上是 sox 的别名,默认输出到 default device)
// Windows: sox -t raw ... -d (显式指定 -d 输出到 default device)
const args = [
'-t', 'raw', // 输入格式 raw
'-b', '16', // 16 bit
'-e', 'signed', // signed integer
'-c', '1', // 1 channel
'-r', '48000', // 48k sample rate
'-' // 从 stdin 读取
];
if (IS_MAC) {
// macOS 必须显式给出输出设备,否则 SoX 会直接报
// "Not enough input filenames specified" 并立即退出。
args.push('-t', 'coreaudio', macOutputDevice);
} else if (soxUseDefaultDevice) {
// Windows 下如果直接使用 sox.exe,需要添加 -d 参数来指定默认输出设备
// args.push('-d');
// 显式指定 waveaudio default,解决部分系统 "no default audio device configured" 问题
// 优先尝试输出到 VB-CABLE,如果找不到则回退到 default
// 注意:SoX 的 waveaudio 驱动使用设备名称匹配
// 我们尝试直接指定 "CABLE Input (VB-Audio Virtual Cable)"
// 由于 SoX 对设备名称的支持可能受限于版本和编译选项,
// 以及名称中空格的处理,这里使用 env.AUDIODEV 可能更稳妥,或者尝试直接传参
// 策略:如果是在 Windows,我们尝试通过环境变量设置 AUDIODEV
// 或者直接在参数里写。SoX 14.4.2+ on Windows usually supports -t waveaudio "Device Name"
args.push('-t', 'waveaudio');
// 使用 default 作为回退,但为了定向输出,我们尝试指定设备名
// 如果用户没有改名,通常是 "CABLE Input (VB-Audio Virtual Cable)"
// 但为了保险,我们先用 default,并提示用户设置 default device
// 如果要强制路由,需要知道准确的设备名。
// 从之前的 ffmpeg output 看到的名字是 "CABLE Input (VB-Audio Virtual Cable)"
// 尝试直接使用该名称
args.push('CABLE Input (VB-Audio Virtual Cable)');
}
const env = { ...process.env };
if (IS_MAC) {
env.AUDIODEV = macOutputDevice;
} else if (IS_WIN) {
// Windows 下也可以尝试设置 AUDIODEV,但命令行参数优先级更高
// env.AUDIODEV = 'CABLE Input (VB-Audio Virtual Cable)';
}
try {
// 在 Windows 下使用 spawn 时,如果路径包含空格可能会有问题,但这里是直接执行
soxProcess = spawn(soxPath, args, { env });
soxProcess.on('error', (err) => {
console.error(`【SoX错误】启动失败: ${err.message}`);
// Windows 下可能 spawn 失败,回退到 Speaker?
// 这里不做自动回退,让用户看到错误
});
soxProcess.on('close', (code) => {
if (code !== 0 && pipelineState !== 'idle') {
console.error(`【SoX错误】进程异常退出,exit code=${code}`);
}
});
// 忽略 stderr 输出,除非调试需要
soxProcess.stderr.on('data', (data) => {
const msg = data.toString();
// 仅在出错或 Windows 下打印,方便调试
// 屏蔽常规进度信息: "In:0.00%"
if (msg.includes('In:') && msg.includes('Out:')) {
return;
}
// 屏蔽文件头信息
if (msg.includes('Encoding:') || msg.includes('Channels:') || msg.includes('Samplerate:') || msg.includes('File Size:')) {
return;
}
if (IS_WIN || msg.includes('FAIL') || msg.includes('WARN')) {
// 过滤掉一些非关键信息,只保留可能的错误
if (msg.trim().length > 0) {
console.error(`【SoX底层】${msg.trim()}`);
}
}
});
outputStream = soxProcess.stdin;
const deviceName = IS_MAC ? macOutputDevice : 'Default Audio Device (VB-CABLE)';
console.log(`【音频管道】已启动 SoX 进程,定向输出到 ${deviceName}`);
} catch (e) {
console.error(`【SoX异常】${e.message}`);
hasSox = false;
}
}
if (!outputStream) {
console.error('【音频管道】未能初始化音频输出目标,请检查 SoX 和虚拟声卡配置');
cleanupPipeline();
return;
}
// 配置 FFmpeg
// 输入: WebM (来自浏览器)
// 输出: Raw PCM (送给 Speaker/SoX)
ffmpegCommand = ffmpeg(audioStream)
.inputFormat('webm')
.audioCodec('pcm_s16le')
.audioChannels(1)
.audioFrequency(48000)
.format('s16le')
.on('error', (err) => {
if (!err.message.includes('Output stream closed') &&
!err.message.includes('write after end') &&
!err.message.includes('signal SIG') &&
!err.message.includes('ffmpeg exited with code 255')) {
console.error(`【FFmpeg错误】: ${err.message}`);
}
cleanupPipeline();
})
.on('start', () => {
console.log(`【FFmpeg】转码进程启动 (${socket.id})`);
})
.on('end', () => {
cleanupPipeline();
})
.on('close', () => {
cleanupPipeline();
});
// 将 FFmpeg 的输出管道连接到 Speaker/SoX
ffmpegCommand.pipe(outputStream, { end: true });
}
function cleanupPipeline() {
/*
if (speaker) {
if (typeof speaker.close === 'function') {
speaker.close();
} else if (typeof speaker.end === 'function') {
speaker.end();
}
speaker = null;
}
*/
if (soxProcess) {
soxProcess.kill();
soxProcess = null;
}
ffmpegCommand = null;
if (pipelineState !== 'idle') {
pipelineState = 'idle';
}
audioStream = new PassThrough();
}
function stopAudioPipeline() {
if (pipelineState === 'idle') return;
pipelineState = 'stopping';
console.log(`【音频管道】正在停止 (${socket.id})...`);
if (audioStream && !audioStream.destroyed) {
audioStream.end();
}
if (ffmpegCommand) {
ffmpegCommand.kill('SIGTERM');
} else {
cleanupPipeline();
}
}
socket.on('start-stream', () => {
console.log(`【指令】收到开始推流请求 (${socket.id})`);
desiredStreaming = true;
if (pipelineState === 'idle') {
pipelineState = 'starting';
audioStream = new PassThrough();
}
});
socket.on('audio-chunk', (data) => {
// data 是 ArrayBuffer 或 Buffer
if (audioStream && !audioStream.destroyed) {
if (desiredStreaming && pipelineState === 'starting' && !ffmpegCommand) {
startAudioPipeline();
}
if (desiredStreaming) {
audioStream.write(data);
}
}
});
socket.on('stop-stream', () => {
console.log(`【指令】收到停止推流请求 (${socket.id})`);
desiredStreaming = false;
stopAudioPipeline();
});
socket.on('disconnect', () => {
console.log(`【连接管理】客户端断开 ID: ${socket.id}`);
stopAudioPipeline();
});
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`-----------------------------------------------------`);
console.log(`【服务启动】HTTPS 服务器运行在 https://${getLocalIP()}:${PORT}`);
console.log(`【重要提示】`);
if (IS_MAC) {
console.log(`1. 请确保已安装 ffmpeg (brew install ffmpeg)`);
console.log(`2. 请将系统默认音频输出设置为 'BlackHole'`);
} else if (IS_WIN) {
if (!hasFfmpeg) console.log(`1. 未检测到 ffmpeg,请参考上文警告进行配置`);
console.log(`2. 请将系统默认音频输出设置为 'VB-CABLE'`);
}
console.log(`3. 手机需连接同一 Wi-Fi,访问上面的 IP 地址`);
console.log(OUTPUT_HINT);
console.log(`-----------------------------------------------------`);
});
} catch (err) {
console.error('【系统启动失败】', err);
}
}
if (require.main === module) {
startServer();
}
// 获取局域网Ip
function getLocalIP() {
const os = require('os');
const networkInterfaces = os.networkInterfaces();
for (const interfaceName in networkInterfaces) {
const interfaceInfo = networkInterfaces[interfaceName];
for (const addressInfo of interfaceInfo) {
if (addressInfo.family === 'IPv4' && !addressInfo.internal) {
return addressInfo.address;
}
}
}
return '0.0.0.0';
}
module.exports = { startServer };