Featured image of post 小玩具:在macos13下实现跨平台音频串流

小玩具:在macos13下实现跨平台音频串流

最近把老黑果主机拿出来做测试了,但是可能是驱动问题,老主板所有音频接口都输出不了,只能从 HDMI 输出,挺麻烦的。既然物理办法无效,而且我暂时也没有能用的蓝牙耳机,只能开始寻找能传输音频的办法

前言

最近把老黑果主机拿出来做测试了,但是可能是驱动问题,老主板所有音频接口都输出不了,只能从 HDMI 输出,挺麻烦的。既然物理办法无效,而且我暂时也没有能用的蓝牙耳机,只能开始寻找能传输音频的办法。

省流

完整项目已上传到 GH 点我右转

BlackHole

众所周知(我才不管你知不知道),macos 不让 app 获得系统音频,比如 soundit 就没有 mac 版本。但是可以创建一个虚拟音频设备来欺骗系统,比如 BlackHole,我的话就下载双通道版本就好。有了这个音频设备就可以进行捕获推流了,比如 obs 推 rtmp,ffmpeg 处理串流转发。

ffmpeg 麻烦

我现在需要的是,将 macos 的音频串流转发到 windows,然后在笔记本上用耳机听到声音。OBS 可以捕获音频推 RTMP 但是我不想装 OBS,本来硬盘就没多大,装一个没用的软件对我是一种心理负担,所以就把目光看到了 ffmpeg。

在 windows 端用 ffplay 创建 TCP 监听

1
ffplay -f wav "tcp://0.0.0.0:12345?listen=1"

在 mac 端用 ffmpeg 创建捕获并发送 [PCM]

1
ffmpeg -f avfoundation -i ":BlackHole 2ch" -acodec pcm_s16le -ar 44100 -ac 2 -f wav -flush_packets 1 "tcp://192.168.10.64:12345"

其实这个时候已经初步达到效果了,但是 ffmpeg 使用的 avfoundation 录制方法会有电流声,再加上黑果的网卡很烂,时延一下稳一下跑到 30ms,还时不时给你来点抖动,听感稳的时候还行,烂的时候耳朵都要电麻了。显然 ffmpeg 这种傻白甜的办法不太适合黑果环境。

audiorelay

ffmpeg 折腾了几个小时发现实在没法调优之后,我只能开始找找有没有什么成熟的应用。然后就发现了这个audiorelay 他是支持三端中继的,然后也是需要 BlackHole 才能捕获试了一下效果居然还不错,没有 ffmpeg 那种电耳朵,只是偶尔会因为环境丢包严重卡顿一下。这也算是一个方案吧,查了一下想知道怎么做的,然后看到用的是 Kotlin 的音频框架,看不懂随劝退…

go 实现

audiorelay 能跑起来增加了我很多信心,不就是捕获音频然后网络串流转发吗?既然这个软件在黑果上跑的这么好,那显然 BlackHole 这个虚拟音频本身是没问题的,那么试着自己写一下而不经过 ffmpeg 呢?所以就开始翻 go 这边有什么能捕获音频的轮子,然后自己拼好轮优化了一下。

PortAudio 和 oto

https://files.portaudio.com/docs/v19-doxydocs/tutorial_start.html

有这么一个 C++音频库是支持 macos,然后刚好有大佬做了 go 封装实现

https://pkg.go.dev/github.com/gordonklaus/portaudio

再用 oto 音效库播放流媒体 https://github.com/ebitengine/oto

报错 Input overflowed

有时候传输一段时间后会出现 Audio read error: Input overflowed 。通常是因为网络不稳定断连导致缓冲堆积处理不过来,主要是黑果的网卡太古老了,比如播放视频,大文件下载,带宽就不够用,macos 又调整不了网络优先级。所以如果你的环境实在太差,但是你想要更稳定的传输质量,要么就下降传输质量(我不接受)或者更推荐的安装方式是用一根网线,或者如果你有第二张网卡来直连两台计算机。另外推荐一个开源的跨端键鼠共享,适合用来操作看文档,不过目前遇到一些问题就是光标没法操作系统对话框,包括 vscode 也是无反应 lan-mouse 现在更推荐input-leap 如果你下载 release,请注意不要用 3.0.3 用 3.0.2,最新版本是 debug 版不带依赖很坑。

简单实现:

服务端放在 macos 监听 TCP 端口 12345

播放端放在 window 用 oto 库来播放 tcp 接收的音频

理论上可以跨平台使用 不过需要自己解决 Portaudio 依赖

Go-PlayBack(windows):

  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
package main

import (
	"fmt"
	"io"
	"net"
	"time"

	"github.com/ebitengine/oto/v3"
)

type AudioClient struct {
	conn       net.Conn
	context    *oto.Context
	player     *oto.Player
	sampleRate int
	channels   int
	serverAddr string
	bytesRead  int64
	startTime  time.Time
}

func NewAudioClient() *AudioClient {
	return &AudioClient{
		sampleRate: 48000,
		channels:   2,
		startTime:  time.Now(),
	}
}

func (ac *AudioClient) Connect(server string) error {
	ac.serverAddr = server
	return ac.reconnect()
}

func (ac *AudioClient) reconnect() error {
	if ac.conn != nil {
		ac.conn.Close()
		ac.conn = nil
	}

	conn, err := net.Dial("tcp", ac.serverAddr)
	if err != nil {
		return err
	}
	ac.conn = conn

	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.SetNoDelay(true)
		tcpConn.SetReadBuffer(128 * 1024)
		tcpConn.SetWriteBuffer(64 * 1024)
		tcpConn.SetKeepAlive(true)
	}

	if ac.context == nil {
		op := &oto.NewContextOptions{
			SampleRate:   ac.sampleRate,
			ChannelCount: ac.channels,
			Format:       oto.FormatSignedInt16LE,
		}

		ctx, ready, err := oto.NewContext(op)
		if err != nil {
			ac.conn.Close()
			return fmt.Errorf("failed to create audio context: %v", err)
		}
		<-ready
		ac.context = ctx
	}

	if ac.player != nil {
		ac.player.Close()
	}
	ac.player = ac.context.NewPlayer(ac)

	ac.player.Play()

	fmt.Printf("Connected to audio server %s (Sample rate: %dHz)\n", ac.serverAddr, ac.sampleRate)
	return nil
}

func (ac *AudioClient) Read(p []byte) (int, error) {
	if ac.conn == nil {
		return 0, io.EOF
	}

	ac.conn.SetReadDeadline(time.Now().Add(3 * time.Second))

	n, err := ac.conn.Read(p)
	if err != nil {
		if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
			return 0, nil
		}
		if err == io.EOF {
			fmt.Println("Server closed connection")
			return 0, io.EOF
		}
		fmt.Printf("Read error: %v\n", err)
		return 0, err
	}

	ac.bytesRead += int64(n)
	return n, nil
}

func (ac *AudioClient) getNetworkStats() string {
	if ac.conn == nil {
		return "Connection: Disconnected"
	}

	duration := time.Since(ac.startTime).Seconds()
	if duration < 1 {
		duration = 1
	}

	bytesPerSec := float64(ac.bytesRead) / duration
	kbps := (bytesPerSec * 8) / 1024

	remoteAddr := "Unknown"
	if ac.conn.RemoteAddr() != nil {
		remoteAddr = ac.conn.RemoteAddr().String()
	}

	return fmt.Sprintf("Connection: Active | Remote: %s | Data Rate: %.1f kbps",
		remoteAddr, kbps)
}

func (ac *AudioClient) StartPlayback() {
	fmt.Println("Starting playback...")

	errorCount := 0
	maxErrors := 5
	reconnectDelay := time.Second * 5
	lastStatsPrint := time.Now()
	statsInterval := 10 * time.Second

	for {
		if !ac.player.IsPlaying() {
			errorCount++
			fmt.Printf("Player stopped (error count: %d)\n", errorCount)

			if errorCount > maxErrors {
				fmt.Println("Player stopped multiple times, exiting")
				break
			}

			ac.player.Play()
			time.Sleep(100 * time.Millisecond)
			continue
		}

		errorCount = 0

		if ac.conn == nil {
			fmt.Printf("Connection lost, attempting to reconnect in %v...\n", reconnectDelay)
			time.Sleep(reconnectDelay)

			if err := ac.reconnect(); err != nil {
				fmt.Printf("Reconnection failed: %v\n", err)
				reconnectDelay *= 2
				if reconnectDelay > 30*time.Second {
					reconnectDelay = 30 * time.Second
				}
				continue
			}

			reconnectDelay = 5 * time.Second
			fmt.Println("Reconnected successfully")
		}

		if time.Since(lastStatsPrint) > statsInterval {
			fmt.Println(ac.getNetworkStats())
			lastStatsPrint = time.Now()
		}

		time.Sleep(1 * time.Second)
	}
}

func (ac *AudioClient) Close() {
	if ac.player != nil {
		ac.player.Pause()
		time.Sleep(100 * time.Millisecond)
		ac.player.Close()
		fmt.Println("Player closed")
	}
	if ac.conn != nil {
		ac.conn.Close()
		fmt.Println("Connection closed")
	}
}

func main() {
	client := NewAudioClient()
	defer client.Close()

	fmt.Println("Starting audio client (Oto v3)")
	fmt.Println("=====================")

	maxRetries := 3
	initialRetryDelay := time.Second * 5

	for i := 0; i < maxRetries; i++ {
		if err := client.Connect("192.168.10.72:12345"); err != nil {
			fmt.Printf("Connection failed (attempt %d): %v\n", i+1, err)
			if i < maxRetries-1 {
				retryDelay := initialRetryDelay * time.Duration(i+1)
				fmt.Printf("Retrying in %v...\n", retryDelay)
				time.Sleep(retryDelay)
				continue
			}
			fmt.Println("Max connection retries reached, exiting")
			return
		}
		break
	}

	client.StartPlayback()
}

Go-Server(macos):

  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
package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gordonklaus/portaudio"
)

type AudioRelay struct {
	// TCP
	listener  net.Listener      // TCP监听器,用于接受客户端连接
	clients   map[net.Conn]bool // 已连接的客户端
	clientsMu sync.RWMutex      // 客户端集合的读写锁

	// 音频流
	stream     *portaudio.Stream // PortAudio捕获音频实例
	sampleRate float64           // 采样率
	channels   int               // 声道数
	bufferSize int               // 缓冲区大小
	isRunning  bool              // 运行状态标

	devices []*portaudio.DeviceInfo // 可用输入设备列表

	// 音频捕获控制
	captureStarted bool                  // 捕获状态
	captureMutex   sync.RWMutex          // 捕获状态的读写锁
	selectedDevice *portaudio.DeviceInfo // 选择音频输入设备
}

func NewAudioRelay() *AudioRelay {
	if err := portaudio.Initialize(); err != nil {
		log.Printf("Error: PortAudio initialization failed: %v", err)
	}

	return &AudioRelay{
		clients:        make(map[net.Conn]bool),
		sampleRate:     48000,
		channels:       2,
		bufferSize:     1024,
		isRunning:      false,
		captureStarted: false,
	}
}

// 获取输入设备
func (n *AudioRelay) GetInputDevices() ([]*portaudio.DeviceInfo, error) {
	allDevices, err := portaudio.Devices()
	if err != nil {
		return nil, fmt.Errorf("failed to get input device list: %v", err)
	}

	var inputDevices []*portaudio.DeviceInfo
	for _, device := range allDevices {
		if device.MaxInputChannels > 0 {
			inputDevices = append(inputDevices, device)
		}
	}

	n.devices = inputDevices
	return inputDevices, nil
}

// 选择设备
func (n *AudioRelay) SelectInputDevice() (*portaudio.DeviceInfo, error) {
	devices, err := n.GetInputDevices()
	if err != nil {
		return nil, err
	}

	if len(devices) == 0 {
		return nil, fmt.Errorf(" No available input devices found")
	}

	fmt.Println("\n🎧 Currently available audio devices:")
	fmt.Println("\n ")

	for i, device := range devices {
		defaultMarker := ""
		defaultDevice, err := portaudio.DefaultInputDevice()
		if err == nil && device.Name == defaultDevice.Name {
			defaultMarker = " (default)"
		}

		fmt.Printf("[%d] %s%s\n", i, device.Name, defaultMarker)
		fmt.Printf("    Input Channels: %d, Sample Rate: %.0f Hz API: %s\n",
			device.MaxInputChannels, device.DefaultSampleRate,
			device.HostApi.Name)
		fmt.Println()
	}

	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Print("Input Device number (q to quit): ")
		input, _ := reader.ReadString('\n')
		input = strings.TrimSpace(input)

		if strings.ToLower(input) == "q" {
			return nil, fmt.Errorf("operation cancelled by user")
		}

		index, err := strconv.Atoi(input)
		if err != nil || index < 0 || index >= len(devices) {
			fmt.Printf("X Invalid choice, enter 0-%d\n", len(devices)-1)
			continue
		}

		selectedDevice := devices[index]

		fmt.Printf("\n √ Selected: %s\n", selectedDevice.Name)

		// 显示设备详细信息
		n.DisplayDeviceInfo(selectedDevice)

		return selectedDevice, nil
	}
}

// 检测BlackHole设备
func (n *AudioRelay) AutoDetectBlackHole() *portaudio.DeviceInfo {
	blackHoleNames := []string{
		"BlackHole 2ch",
		"BlackHole 16ch",
		"BlackHole",
	}

	for _, device := range n.devices {
		for _, name := range blackHoleNames {
			if strings.Contains(strings.ToLower(device.Name), strings.ToLower(name)) {
				return device
			}
		}
	}
	return nil
}

// 获取本机IP地址
func (n *AudioRelay) getLocalIPs() ([]string, error) {
	var ips []string

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, err
	}

	for _, addr := range addrs {
		ipNet, ok := addr.(*net.IPNet)
		if ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				// 只显示IPv4地址
				ips = append(ips, ipNet.IP.String())
			}
		}
	}

	if len(ips) == 0 {
		return nil, fmt.Errorf("no local IPs found")
	}

	return ips, nil
}

// 显示设备详细信息
func (n *AudioRelay) DisplayDeviceInfo(device *portaudio.DeviceInfo) {
	fmt.Printf("\n Details:\n")
	fmt.Printf("   Name: %s\n", device.Name)
	fmt.Printf("   Input Channels: %d\n", device.MaxInputChannels)
	fmt.Printf("   Output Channels: %d\n", device.MaxOutputChannels)
	fmt.Printf("   Sample Rate: %.0f Hz\n", device.DefaultSampleRate)
	fmt.Printf("   Low Latency: %.1f ms\n", device.DefaultLowInputLatency.Seconds()*1000)
	fmt.Printf("   High Latency: %.1f ms\n", device.DefaultHighInputLatency.Seconds()*1000)
	fmt.Printf("   Host API: %s\n", device.HostApi.Name)
	fmt.Println()
}

// 启动音频捕获(使用指定设备)
func (n *AudioRelay) StartAudioCaptureWithDevice(device *portaudio.DeviceInfo) error {
	buffer := make([]int16, n.bufferSize*n.channels)

	fmt.Printf("   Using audio device: %s\n", device.Name)
	fmt.Printf("   Sample Rate: %.0f Hz, Channels: %d, Buffer: %d samples\n",
		n.sampleRate, n.channels, n.bufferSize)

	stream, err := portaudio.OpenStream(
		portaudio.StreamParameters{
			Input: portaudio.StreamDeviceParameters{
				Device:   device,
				Channels: n.channels,
				Latency:  device.DefaultLowInputLatency,
			},
			SampleRate:      n.sampleRate,
			FramesPerBuffer: len(buffer),
		},
		buffer,
	)
	if err != nil {
		return fmt.Errorf("failed to open audio stream: %v", err)
	}

	n.stream = stream
	n.isRunning = true

	if err := stream.Start(); err != nil {
		return fmt.Errorf(" X failed to start audio stream: %v", err)
	}

	fmt.Println(" √ Audio capture started")

	go n.processAudio(buffer)
	return nil
}

// 启动音频捕获(等待客户端)
func (n *AudioRelay) checkAndStartCapture() {
	n.captureMutex.Lock()
	defer n.captureMutex.Unlock()

	if !n.captureStarted && n.getClientCount() > 0 {
		fmt.Println("Client connected, starting audio capture...")
		if err := n.StartAudioCaptureWithDevice(n.selectedDevice); err != nil {
			log.Printf("Failed to start audio capture: %v", err)
			return
		}
		n.captureStarted = true
	}
}

// 停止音频捕获(客户端断开)
func (n *AudioRelay) checkAndStopCapture() {
	n.captureMutex.Lock()
	defer n.captureMutex.Unlock()

	if n.captureStarted && n.getClientCount() == 0 {
		fmt.Println("⏸️ All clients disconnected, stopping audio capture...")
		if n.stream != nil {
			n.stream.Stop()
			n.stream.Close()
			n.stream = nil
		}
		n.captureStarted = false
	}
}

func (n *AudioRelay) processAudio(buffer []int16) {
	frameCount := 0
	lastStats := time.Now()
	bytesTransferred := 0
	silenceFrames := 0

	for n.isRunning {
		if n.getClientCount() == 0 {
			fmt.Println(" ⏸ No clients connected, stopping audio processing")
			n.captureMutex.Lock()
			n.captureStarted = false
			if n.stream != nil {
				n.stream.Stop()
				n.stream.Close()
				n.stream = nil
			}
			n.captureMutex.Unlock()
			return
		}

		if err := n.stream.Read(); err != nil {
			log.Printf("Read error: %v", err)
			time.Sleep(10 * time.Millisecond)
			continue
		}

		frameCount++

		// 静音判断
		if n.isSilence(buffer) {
			silenceFrames++
			// 连续静音,尝试跳过处理以减少带宽
			if silenceFrames > 10 {
				continue
			}
		} else {
			silenceFrames = 0
		}

		// 处理音频数据
		processedBuffer := n.processAudioData(buffer)
		audioData := n.int16ToBytes(processedBuffer)
		bytesTransferred += len(audioData)

		// 广播给客户端
		n.broadcastToClients(audioData)

		// 显示统计信息
		if time.Since(lastStats) > 3*time.Second {
			rate := float64(bytesTransferred) / time.Since(lastStats).Seconds() / 1024
			clientCount := n.getClientCount()

			status := "Normal"
			if silenceFrames > 0 {
				status = "Abnormal"
			}

			fmt.Printf("Status: %s Frames: %d, Rate: %.1f KB/s, Clients: %d\n",
				status, frameCount, rate, clientCount)

			bytesTransferred = 0
			lastStats = time.Now()
		}
	}
}

// 检查静音
func (n *AudioRelay) isSilence(buffer []int16) bool {
	const silenceThreshold = 1000 // 静音阈值
	for i := 0; i < len(buffer); i++ {
		if buffer[i] > silenceThreshold || buffer[i] < -silenceThreshold {
			return false
		}
	}
	return true
}

func (n *AudioRelay) processAudioData(buffer []int16) []int16 {
	processed := make([]int16, len(buffer))
	copy(processed, buffer)

	for i := range processed {
		// 降低音量
		processed[i] = int16(float64(processed[i]) * 0.8)

		// 限幅
		if processed[i] > 28000 {
			processed[i] = 28000
		} else if processed[i] < -28000 {
			processed[i] = -28000
		}
	}

	return processed
}

func (n *AudioRelay) int16ToBytes(buffer []int16) []byte {
	bytes := make([]byte, len(buffer)*2)
	for i, sample := range buffer {
		bytes[i*2] = byte(sample & 0xFF)
		bytes[i*2+1] = byte((sample >> 8) & 0xFF)
	}
	return bytes
}

func (n *AudioRelay) broadcastToClients(data []byte) {
	n.clientsMu.RLock()
	defer n.clientsMu.RUnlock()

	if len(n.clients) == 0 {
		return
	}

	failedClients := make([]net.Conn, 0)

	for client := range n.clients {
		client.SetWriteDeadline(time.Now().Add(2 * time.Second))
		_, err := client.Write(data)
		if err != nil {
			failedClients = append(failedClients, client)
		}
	}

	if len(failedClients) > 0 {
		go n.cleanupClients(failedClients)
	}
}

func (n *AudioRelay) cleanupClients(failedClients []net.Conn) {
	n.clientsMu.Lock()
	defer n.clientsMu.Unlock()

	for _, client := range failedClients {
		delete(n.clients, client)
		client.Close()
		fmt.Printf("Client disconnected: %s\n", client.RemoteAddr())
	}

	// 是否需要停止音频捕获
	if len(n.clients) == 0 {
		go n.checkAndStopCapture()
	}
}

func (n *AudioRelay) getClientCount() int {
	n.clientsMu.RLock()
	defer n.clientsMu.RUnlock()
	return len(n.clients)
}

func (n *AudioRelay) StartTCPServer(port string) error {
	var err error
	n.listener, err = net.Listen("tcp", ":"+port)
	if err != nil {
		return err
	}
	fmt.Printf("TCP listening on port %s \n", port)

	if ips, err := n.getLocalIPs(); err == nil {
		fmt.Printf("Server addresses:\n")
		for _, ip := range ips {
			fmt.Printf("http://%s:%s\n", ip, port)
		}
	} else {
		fmt.Printf("Server address: 0.0.0.0:%s\n", port)
	}
	return nil
}

func (n *AudioRelay) AcceptClients() {
	for {
		conn, err := n.listener.Accept()
		if err != nil {
			if n.isRunning {
				log.Printf("Client connection error: %v", err)
			}
			return
		}

		if tcpConn, ok := conn.(*net.TCPConn); ok {
			tcpConn.SetNoDelay(true)
			tcpConn.SetWriteBuffer(32 * 1024)
			tcpConn.SetReadBuffer(16 * 1024)
			tcpConn.SetKeepAlive(true)
		}

		fmt.Printf(" √ Client connected: %s\n", conn.RemoteAddr())
		n.addClient(conn)

		// 检查是否需要启动音频捕获
		go n.checkAndStartCapture()
	}
}

func (n *AudioRelay) addClient(conn net.Conn) {
	n.clientsMu.Lock()
	defer n.clientsMu.Unlock()
	n.clients[conn] = true
}

func (n *AudioRelay) Start() error {
	fmt.Println("👊 Welcome to the audio relay —— xiaolin")
	fmt.Println("=====================")

	// 让用户选择输入设备
	selectedDevice, err := n.SelectInputDevice()
	if err != nil {
		return fmt.Errorf("device selection failed: %v", err)
	}
	n.selectedDevice = selectedDevice

	// 启动TCP服务器
	if err := n.StartTCPServer("12345"); err != nil {
		return err
	}

	// 开始接受客户端连接
	go n.AcceptClients()
	fmt.Println("Service started,")
	fmt.Println("Waiting for receiving clients...")
	select {}
}

func (n *AudioRelay) Stop() {
	fmt.Println("Stopping service...")
	n.isRunning = false

	if n.stream != nil {
		n.stream.Stop()
		n.stream.Close()
		fmt.Println("Audio stream closed")
	}

	if n.listener != nil {
		n.listener.Close()
		fmt.Println("TCP server closed")
	}

	n.clientsMu.Lock()
	for client := range n.clients {
		client.Close()
	}
	n.clients = make(map[net.Conn]bool)
	n.clientsMu.Unlock()

	portaudio.Terminate()
	fmt.Println("Service fully stopped")
}

func main() {
	relay := NewAudioRelay()
	defer relay.Stop()

	defer func() {
		if r := recover(); r != nil {
			log.Printf("Program crashed: %v", r)
		}
	}()

	if err := relay.Start(); err != nil {
		log.Fatalf("Failed to start: %v", err)
	}
}
Licensed under CC BY-NC-SA 4.0