{"id":1329,"date":"2025-07-08T20:39:51","date_gmt":"2025-07-08T12:39:51","guid":{"rendered":"https:\/\/imuslab.com\/wordpress\/?p=1329"},"modified":"2025-07-08T20:43:08","modified_gmt":"2025-07-08T12:43:08","slug":"pcm-over-websocket","status":"publish","type":"post","link":"https:\/\/imuslab.com\/wordpress\/2025\/07\/08\/pcm-over-websocket\/","title":{"rendered":"Golang \u900f\u904e WebSocket \u4e32\u6d41 PCM Audio Stream \u5230 Web UI"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"592\" src=\"https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1024x592.png\" alt=\"\" class=\"wp-image-1330\" srcset=\"https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1024x592.png 1024w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-300x173.png 300w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-768x444.png 768w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1536x887.png 1536w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1200x693.png 1200w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247.png 1603w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>RemdesKVM \uff08P.S.\u9019\u662f\u4e00\u500b\u7db2\u9801\uff09<\/figcaption><\/figure>\n\n\n\n<p>\u6700\u8fd1\u56e0\u70ba\u5728\u958b\u767c RemdesKVM \uff08\u4e00\u5957\u958b\u6e90\u7684 IP-KVM \u88dd\u7f6e\uff09\uff0c\u6240\u4ee5\u9700\u8981\u60f3\u8fa6\u6cd5\u5728 Linux \u4e0b\u628a USB HDMI capture card \u7684 audio stream \u4e32\u6d41\u5230 Web UI\u3002\u807d\u4e0a\u53bb\u597d\u50cf\u5f88\u7c21\u55ae\uff0c\u4f46\u662f\u60f3\u4e0d\u5230\u5be6\u969b\u4e0a\u505a\u8d77\u4f86\u4e00\u9ede\u4e5f\u4e0d\u5bb9\u6613\uff08<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u70ba\u751a\u9ebc\u5148\u4e0d\u7528 WebRTC\uff1f<\/h3>\n\n\n\n<p>\u5982\u679c\u4f60\u8ddf\u4e00\u500b\u73fe\u4ee3\u7684 Web Developer \u8b1b\u9019\u529f\u80fd\uff0c\u4ed6\u7b2c\u4e00\u6642\u9593\u56de\u8986\u4f60\u7684\u7576\u7136\u5c31\u662f WebRTC \u4e86\u3002WebRTC \u662f\u4e00\u7a2e\u57fa\u65bc UDP \u7684\u6280\u8853\uff0c\u5bb9\u8a31 Server \u8ddf Client \u4e4b\u9593\u900f\u904e UDP \u9032\u884c real-time communication &amp; streaming\u3002\u90a3\u4e5f\u662f\u56e0\u70ba UDP \u7684\u95dc\u7cfb\uff0c\u6240\u4ee5 packet \u5c31\u662f\u9001\u51fa\u53bb\u5c31\u4e0d\u7406\u4e86\uff0c\u81ea\u7136\u5c31\u4e0d\u6703\u6709\u592a\u5927\u7684 latency \u554f\u984c\u3002\u7136\u800c\u4f7f\u7528 WebRTC \u5354\u8b70\u6703\u51fa\u73fe\u5169\u500b\u554f\u984c\uff1a<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>HTTP \u662f\u57fa\u65bc TCP\uff0c\u56e0\u6b64\u5982\u679c\u672c\u8eab\u4f60\u5df2\u7d93\u6709\u6574\u5957 HTTP proxy \/ routing infrastructure\uff0c\u4f7f\u7528 UDP \u5c31\u8981\u984d\u5916\u518d\u589e\u52a0\u4e00\u5957 proxying services \uff08\u96d6\u7136 Zoraxy \u8ddf NPM \u4e4b\u985e\u7684\u90fd\u6709 build-in \u5c31\u662f\u4e86\uff09<\/li><li>WebRTC \u9700\u8981 opus \uff08\u7136\u5f8c opus \u6c92\u6709 go native \u7684 encoder implementation\uff09<\/li><\/ol>\n\n\n\n<p>\u6240\u4ee5\u9019\u88e1\u6211\u5148\u4f7f\u7528\u4e86\u57fa\u65bc websocket \u7684\u65b9\u6848\uff0c\u4e4b\u5f8c\u6709\u7a7a\u518d\u4f86\u5f04 WebRTC \u7684\u65b9\u6848\u3002<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Alsa \u8207 Linux Audio Device<\/h2>\n\n\n\n<p>\u5728\u771f\u6b63\u8b1b\u5230\u600e\u6a23\u4e32\u6d41\u4e4b\u524d\uff0c\u5148\u8b1b\u4e00\u4e0b\u6211\u600e\u6a23\u5f9e USB HDMI device \u6293\u51fa PCM data\u3002\u7c21\u55ae\u4f86\u8aaa\u5728 Linux \u88e1\u9762 everything is a file\uff0c\u6240\u4ee5\u81ea\u7136\u5730\u4f60\u53ef\u4ee5\u5f9e \/dev\/snd\/ \u88e1\u9762\u5176\u4e2d\u4e00\u500b\u88dd\u7f6e\u6293\u5230\u4f60\u9700\u8981\u7684 PCM \u8cc7\u6599\u3002\u6211\u9019\u88e1\u7528\u7684\u662f arecord \u5de5\u5177\uff0c\u53ef\u4ee5\u900f\u904e\u4ee5\u4e0b\u6307\u4ee4\u5b89\u88dd\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt install alsa-utils<\/code><\/pre>\n\n\n\n<p>\u4e4b\u5f8c\u5c31\u662f\u900f\u904e -l \u6307\u4ee4\u5217\u51fa\u6240\u6709 Audio device<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ arecord -l\n**** List of CAPTURE Hardware Devices ****\ncard 0: sofhdadsp [sof-hda-dsp], device 0: HDA Analog (*) []\n  Subdevices: 1\/1\n  Subdevice #0: subdevice #0\ncard 0: sofhdadsp [sof-hda-dsp], device 6: DMIC (*) []\n  Subdevices: 1\/1\n  Subdevice #0: subdevice #0\ncard 0: sofhdadsp [sof-hda-dsp], device 7: DMIC16kHz (*) []\n  Subdevices: 1\/1\n  Subdevice #0: subdevice #0\ncard 1: MS2109 [MS2109], device 0: USB Audio [USB Audio]\n  Subdevices: 0\/1\n  Subdevice #0: subdevice #0<\/code><\/pre>\n\n\n\n<p>\u9019\u88e1\u53ef\u4ee5\u770b\u5230\uff0c\u6211\u5728\u7528\u7684 USB HDMI capture device \u662f\u57fa\u65bc MS2109 \u7684\u8d85\u4fbf\u5b9c capture card\u3002\u5b83\u7684\u4f4d\u7f6e\u5c31\u662f card 1, subdevices 0\u3002\u7136\u5f8c\u6211\u5011\u5c31\u662f\u8981\u6e2c\u8a66\u770b\u770b\u5b83\u662f\u4e0d\u662f\u771f\u7684\u80fd\u5920 capture \u5230 audio data\u3002<\/p>\n\n\n\n<p>\u6839\u64da\u9019\u9846 IC \u7684 datasheet\uff0c\u6211\u5011\u77e5\u9053\u9019\u500b\u88dd\u7f6e\u652f\u63f4 48kHz 2 channel audio \u7684 sampling rate\uff0c\u9019\u500b\u6642\u5019\u53ef\u4ee5\u7528\u9019\u500b\u6307\u4ee4\u4f86\u63a1\u96c6\u88dd\u7f6e\u7684 capture audio \u5230 test.wav \uff08\u6ce8\uff1a\u6309 Ctrl + C \u505c\u6b62\u4e26\u5132\u5b58\uff09<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>arecord -D hw:1,0 -f S16_LE -r 48000 -c 2 test.wav<\/code><\/pre>\n\n\n\n<p>\u7136\u5f8c\u5982\u679c\u4f60\u5728\u88ab capture \u7684\u88dd\u7f6e\u4e0a\u64ad\u653e\u97f3\u6a02\uff0c\u9019\u6bb5\u97f3\u6a02\u4fbf\u6703\u51fa\u73fe\u5728\u88ab capture \u7684 test.wav \u6a94\u5167\u3002\u9019\u88e1\u70ba\u4e86\u65b9\u4fbf Golang \u81ea\u52d5\u6293\u6b63\u78ba\u7684 audio device \u6211\u5beb\u4e86\u500b\u9019\u6a23\u7684 filter function \u4f86\u76f4\u63a5\u7d66\u6211\u7522\u751f\u9700\u8981\u7684 &#8220;hw:1,0&#8221; parameter<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ FindHDMICaptureCard searches for an HDMI capture card using the `arecord -l` command.\nfunc FindHDMICapturePCMPath() (string, error) {\n\tout, err := exec.Command(\"arecord\", \"-l\").Output()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"arecord -l failed: %w\", err)\n\t}\n\n\tlines := strings.Split(string(out), \"\\n\")\n\tfor _, line := range lines {\n\t\tlower := strings.ToLower(line)\n\t\tif strings.Contains(lower, \"ms2109\") || strings.Contains(lower, \"ms2130\") {\n\t\t\t\/\/ Example line:\n\t\t\t\/\/ card 1: MS2109 [MS2109], device 0: USB Audio [USB Audio]\n\t\t\tparts := strings.Fields(line)\n\t\t\tvar cardNum, devNum string\n\t\t\tfor i := range parts {\n\t\t\t\tif parts[i] == \"card\" &amp;&amp; i+1 &lt; len(parts) {\n\t\t\t\t\tcardNum = parts[i+1][:1] \/\/ \"1\"\n\t\t\t\t}\n\t\t\t\tif parts[i] == \"device\" &amp;&amp; i+1 &lt; len(parts) {\n\t\t\t\t\tdevNum = strings.TrimSuffix(parts[i+1], \":\") \/\/ \"0\"\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif cardNum != \"\" &amp;&amp; devNum != \"\" {\n\t\t\t\treturn fmt.Sprintf(\"\/dev\/snd\/pcmC%vD%vc\", cardNum, devNum), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"no HDMI capture card found\")\n}\n\n\/\/ Convert a PCM device name to a hardware device name.\n\/\/ Example: \"pcmC1D0c\" -> \"hw:1,0\"\nfunc pcmDeviceToHW(dev string) (string, error) {\n\t\/\/ Regex to extract card and device numbers\n\tre := regexp.MustCompile(`pcmC(\\d+)D(\\d+)[cp]`)\n\tmatches := re.FindStringSubmatch(dev)\n\tif len(matches) &lt; 3 {\n\t\treturn \"\", fmt.Errorf(\"invalid device format\")\n\t}\n\tcard := matches[1]\n\tdevice := matches[2]\n\treturn fmt.Sprintf(\"hw:%s,%s\", card, device), nil\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u5728 Golang \u6293\u53d6 PCM data<\/h2>\n\n\n\n<p>\u9019\u500b\u90e8\u5206\u5c31\u6bd4\u8f03\u76f4\u63a5\u4e86\u3002\u65e2\u7136\u6211\u5011\u5df2\u7d93\u77e5\u9053\u4e86\u9019\u500b\u6307\u4ee4\u6703\u8f38\u51fa PCM data\uff0c\u9019\u500b\u6642\u5019\u6211\u5011\u53ea\u8981\u628a\u5b83\u900f\u904e\u628a STDOUT PIPE \u5230 golang \u7684\u4e00\u500b buffer \u5167\u4e0d\u5c31\u53ef\u4ee5\u4e86\u55ce\uff1f\u6240\u4ee5\u5c31\u6709\u4e86\u4ee5\u4e0b\u9019\u6bb5 code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Start arecord with 48Hz, 16-bit, stereo\n\tcmd := exec.Command(\"arecord\",\n\t\t\"-f\", \"S16_LE\", \/\/ Format: 16-bit little-endian\n\t\t\"-r\", fmt.Sprint(i.Config.AudioConfig.SampleRate),\n\t\t\"-c\", fmt.Sprint(i.Config.AudioConfig.Channels),\n\t\t\"-D\", hwdev, \/\/ Use the hardware device\n\t)\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Println(\"Failed to get arecord stdout pipe:\", err)\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Println(\"Failed to start arecord:\", err)\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\treader := bufio.NewReader(stdout)\n\tbufferSize := i.Config.AudioConfig.FrameSize * i.Config.AudioConfig.Channels * i.Config.AudioConfig.BytesPerSample\n\tlog.Printf(\"Buffer size: %d bytes (FrameSize: %d, Channels: %d, BytesPerSample: %d)\",\n\t\tbufferSize, i.Config.AudioConfig.FrameSize, i.Config.AudioConfig.Channels, i.Config.AudioConfig.BytesPerSample)\n\tbuf := make([]byte, bufferSize*2)\n\nfor {\nn, err := reader.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Read error:\", err)\n\t\t\t\tif i.audiostopchan != nil {\n\t\t\t\t\ti.audiostopchan &lt;- true \/\/ Signal to stop the audio pipe\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\nlog.Println(\"Read bytes \", n) \n}<\/code><\/pre>\n\n\n\n<p>\u9019\u88e1\u5148\u5f88\u5feb\u7684\u89e3\u91cb\u4e00\u4e0b\u9019\u500b buffer \u5927\u5c0f\u7684\u539f\u56e0\uff0c\u4ee5\u4e0b\u662f\u9810\u8a2d\u7684 AudioConfig<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>AudioConfig{\n\t\tSampleRate:     48000,\n\t\tChannels:       2,\n\t\tBytesPerSample: 2,    \/\/ 16-bit\n\t\tFrameSize:      1920, \/\/ 1920 samples per frame = 40ms @ 48kHz\n\t}<\/code><\/pre>\n\n\n\n<p>\u9019\u88e1\u5b9a\u7fa9\u4e86\u4f7f\u7528 48khz sampling rate\uff0c2 audio channel (Left &amp; Right) \u548c 16bit PCM \u7684 byte size \uff082bytes)\uff0c\u800c frame size \u5247\u662f\u6211\u5011\u8981 sample \u591a\u4e45\u3002\u9019\u500b framesize \u6703\u6c7a\u5b9a\u6211\u5011\u5148 sample \u591a\u5c11 ms \u518d\u628a\u5b83\u5305\u8d77\u4f86\u9001\u51fa\u53bb\uff0c\u9019\u500b\u6578\u503c\u8d8a\u5927\uff0clatency \u4fbf\u6703\u8d8a\u9ad8\u4f46\u662f\u6578\u64da\u50b3\u8f38\u7684 overhead \uff08\u5982 header\u3001checksum \u7b49\uff09\u4fbf\u6703\u8d8a\u5c0f\uff1b\u800c\u6578\u503c\u8d8a\u5c0f latency \u4fbf\u6703\u8d8a\u4f4e\uff0clatency \u6703\u8b8a\u5c0f\u4f46\u662f overhead \u5c31\u6703\u8b8a\u591a\u3002\u6240\u4ee5\u4e00\u822c\u5728 embedded system \u7684\u74b0\u5883\u4e0b\uff0c\u591a\u6578\u90fd\u662f\u63a1\u7528 40ms frame \u70ba\u6a19\u6e96\uff0c\u4f46\u662f\u50cf Bluetooth Low latency audio \u4e4b\u985e\u7684\u74b0\u5883\u4e0b\uff0c\u6709\u6642\u5019\u6703\u7528\u5230 10ms frame\u3002<\/p>\n\n\n\n<p>\u4e4b\u5f8c\u5c31\u662f\u8981\u8a08\u7b97\u63a1\u96c6 buffer \u7684\u5927\u5c0f\uff0c\u9019\u88e1\u4f7f\u7528 frame \u6578\u91cf x channel \u6578\u91cf x bytes per sample \u4f86\u8a08\u7b97\u3002\u7576\u7136\u5982\u679c\u4f60\u60f3\u4e00\u6b21\u8b80\u53d6\u591a\u500b frame \u4e5f\u53ef\u4ee5\u628a\u9019\u500b <code>bufferSize *= n<\/code> \u4ee5\u6e1b\u5c11 overhead<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bufferSize := i.Config.AudioConfig.FrameSize * i.Config.AudioConfig.Channels * i.Config.AudioConfig.BytesPerSample<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u900f\u904e WebSocket \u50b3\u9001 PCM Data \u5230 Web UI<\/h3>\n\n\n\n<p>\u9019\u500b\u4fbf\u6c92\u751a\u9ebc\u7279\u5225\u4e86\uff0c\u53ea\u662f\u55ae\u7d14\u7684\u628a\u8b80\u53d6\u51fa\u4f86\u7684 PCM bytes \u585e\u5230 websocket \u800c\u5df2\u3002\u9019\u88e1\u7684 example \u63a1\u7528 gorilla websocket packet \u7684 binary \u6a21\u5f0f\u4f86\u50b3\u3002 \u53ea\u8981\u628a for loop \u88e1\u9762\u6539\u6210\u9019\u6a23\u4fbf\u53ef\u4ee5\u4e86\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>n, err := reader.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Read error:\", err)\n\t\t\t\tif i.audiostopchan != nil {\n\t\t\t\t\ti.audiostopchan &lt;- true \/\/ Signal to stop the audio pipe\n\t\t\t\t}\n\t\t\t\tgoto DONE\n\t\t\t}\n\n\t\t\tif n == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/log.Println(\"Read bytes:\", n, \"size of buffer:\", len(buf))\n\t\t\t\/\/Send only the bytes read to WebSocket\n\t\t\terr = conn.WriteMessage(websocket.BinaryMessage, buf[:n])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"WebSocket send error:\", err)\n\t\t\t\tgoto DONE\n\t\t\t}\n\n\/\/DONE \u4f86\u8655\u7406\u4e00\u4e9b clean up \u7684\u6771\u897f<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u524d\u7aef Render PCM data <\/h2>\n\n\n\n<p>\u524d\u7aef\u5728\u6536\u5230 WebSocket \u8cc7\u6599\u5f8c\u8981 render PCM data\uff0c\u9019\u500b\u6642\u5019\u4fbf\u6703\u9700\u8981\u7528\u4e0a Audio Context API\u3002\u9019\u500b API \u5728 Firefox \u4e0a\u901f\u5ea6\u6709\u5920\u6162\uff0c\u6240\u4ee5\u57fa\u672c\u4e0a\u53ea\u6709 Chrome \u624d\u80fd\u6d41\u66a2\u64ad\u653e audio stream\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u5efa\u7acb WebSocket<\/h3>\n\n\n\n<p>\u9019\u500b\u8207\u4e00\u6bb5\u7684 websocket \u5dee\u4e0d\u591a\uff0c\u5c31\u662f\u9700\u8981\u628a binaryType \u5f9e\u9810\u8a2d\u7684 <code>blob<\/code> \u6539\u6210 arraybuffer<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>audioSocket = new WebSocket(audioSocketURL);\naudioSocket.binaryType = 'arraybuffer';\n\n audioSocket.onopen = function() {\n                console.log(\"Audio WebSocket connected\");\n                if (!audioContext) {\n                    audioContext = new (window.AudioContext || window.webkitAudioContext)({sampleRate: 24000});\n                }\n            };<\/code><\/pre>\n\n\n\n<p>\u7136\u5f8c\u5728 onmessage event \u63a5\u6536 PCM data\u3002\u9019\u500b\u6642\u5019\u7684 PCM data \u9084\u662f\u5b83\u539f\u672c\u7684\u72c0\u614b\uff0816bit PCM integer\uff09\uff0c\u4f46\u662f Audio Context \u5403\u7684\u662f Float32 array\uff08range -1 \u5230 1\uff09\uff0c\u6240\u4ee5\u6211\u5011\u9700\u8981\u5148\u628a PCM bytes \u63db\u6210 Float32 array \u624d\u9001\u9032 Audio context render buffer\u3002\u70ba\u4e86\u907f\u514d\u5361\u5230 render routine\uff0c\u6211\u9019\u88e1\u9078\u64c7\u5728\u63a5\u6536\u5230\u7684\u6642\u5019\u5148\u8f49\u63db\u518d\u63a8\u9032 render queue \u5167\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  const MAX_AUDIO_QUEUE = 4;\n  audioSocket.onmessage = function(event) {\n      if (!audioContext) return;\n      let pcm = new Int16Array(event.data);\n      if (pcm.length === 0) {\n          console.warn(\"Received empty PCM data\");\n          return;\n      }\n      if (pcm.length % 2 !== 0) {\n          console.warn(\"Received PCM data with odd length, dropping last sample\");\n          pcm = pcm.slice(0, -1); \/\/ Drop last sample if odd length\n      }\n      \/\/ Convert Int16 PCM to Float32 &#91;-1, 1]\n      let floatBuf = new Float32Array(pcm.length);\n      for (let i = 0; i &lt; pcm.length; i++) {\n          floatBuf&#91;i] = pcm&#91;i] \/ 32768;\n      }\n      \/\/ Limit queue size to prevent memory overflow\n      if (audioQueue.length >= MAX_AUDIO_QUEUE) {\n          audioQueue.shift(); \/\/ Remove oldest audio buffer if queue is full\n      }\n      audioQueue.push(floatBuf);\n      if (!audioPlaying) {\n          audioPlaying = true;\n          playAudioQueue();\n      }\n\n  };<\/code><\/pre>\n\n\n\n<p>\u81f3\u65bc\u8981\u64ad\u653e\u7684\u6642\u5019\u4fbf\u6703\u9700\u8981\u5230\u9019\u500b playAudioQueue \u5167\u7684 function\u3002\u9019\u500b function \u4e5f\u662f\u7c21\u55ae\u76f4\u63a5\u7684<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>\u5f9e audioQueue shift \u4e00\u500b sample \u51fa\u4f86<\/li><li>frame count \u662f\u6211\u5011\u5728\u63a5\u6536\u7684\u6642\u5019\u8f49\u63db\u7684 Float32 buffer \u7684\u4e00\u534a\u9577\u5ea6\uff08\u56e0\u70ba\u6709\u5169\u500b audio channel\uff0cLeft + Right\uff09<\/li><li>\u7136\u5f8c\u6211\u5011\u5efa\u7acb\u4e00\u500b audio context \u7684 2 channel buffer\uff0csampling rate \u662f 48kHz<\/li><li>\u6700\u5f8c\u8b93 audioContext render \u5b83\u51fa\u4f86<\/li><li>\u5b8c\u6210 playback \u5f8c\u518d call \u4e00\u6b21 playAudioQueue() \u4f86\u64ad\u653e\u4e0b\u4e00\u500b PCM frame<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>function playAudioQueue() {\n    if (!audioContext || audioQueue.length == 0) {\n        audioPlaying = false;\n        return;\n    }\n    let floatBuf = audioQueue.shift();\n    let frameCount = floatBuf.length \/ 2;\n    let buffer = audioContext.createBuffer(2, frameCount, 48000);\n    for (let ch = 0; ch &lt; 2; ch++) {\n        let channelData = buffer.getChannelData(ch);\n        for (let i = 0; i &lt; frameCount; i++) {\n            channelData&#91;i] = floatBuf&#91;i * 2 + ch];\n        }\n    }\n    let source = audioContext.createBufferSource();\n    source.buffer = buffer;\n    source.connect(audioContext.destination);\n    source.onended = playAudioQueue;\n    source.start();\n}<\/code><\/pre>\n\n\n\n<p>\u53ef\u662f\u9019\u6a23\u7684 Implementation \u6709\u4e00\u500b\u5c0f bug\uff0c\u5c31\u662f\u5728\u6bcf\u500b 40ms frame \u4e4b\u9593\uff0c\u4f60\u53ef\u4ee5\u807d\u5230\u660e\u986f\u7684\u5361\u4e86\u4e00\u4e0b\u3002\u9019\u500b\u5361\u4e00\u4e0b\u662f\u56e0\u70ba\u6bcf\u6b21 playAudioQueue \u5b83\u90fd\u8981\u5148 allocate memory\u3001decompose PCM bytes \uff08\u90a3\u500b for-loop\uff09\u7136\u5f8c\u624d\u80fd start\u3002\u6240\u4ee5\u70ba\u4e86 optimize \u9019\u500b implementation\uff0c\u6211\u5011\u53ef\u4ee5\u52a0\u4e00\u500b scheduling \u7684\u908f\u8f2f\u9032\u53bb\u8b93\u5b83\u4e00\u9032\u4f86\u99ac\u4e0a\u6392\u9032\u53bb render queue\uff0c\u4e26\u9810\u5148\u5b89\u6392\u597d start audio render \u7684\u6642\u9593\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let scheduledTime = 0;\n\nfunction scheduleAudioPlayback() {\n    if (!audioContext || audioQueue.length === 0) return;\n\n    \/\/ Use audioContext.currentTime to schedule buffers back-to-back\n    if (scheduledTime &lt; audioContext.currentTime) {\n        scheduledTime = audioContext.currentTime;\n    }\n\n    while (audioQueue.length > 0) {\n        let floatBuf = audioQueue.shift();\n        let frameCount = floatBuf.length \/ 2;\n        let buffer = audioContext.createBuffer(2, frameCount, 48000);\n        for (let ch = 0; ch &lt; 2; ch++) {\n            let channelData = buffer.getChannelData(ch);\n            for (let i = 0; i &lt; frameCount; i++) {\n                channelData&#91;i] = floatBuf&#91;i * 2 + ch];\n            }\n        }\n        let source = audioContext.createBufferSource();\n        source.buffer = buffer;\n        source.connect(audioContext.destination);\n        source.start(scheduledTime);\n        scheduledTime += buffer.duration;\n    }\n}\n}<\/code><\/pre>\n\n\n\n<p>\u800c audio websocket \u7684 onmessage \u7684\u90e8\u5206\u6539\u6210\u9019\u6a23 \uff08Queue \u589e\u52a0\u4e86\u4e00\u9ede\u8b93\u5b83\u66f4\u6d41\u66a2\uff09<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const MAX_AUDIO_QUEUE = 8;\naudioSocket.onmessage = function(event) {\n    if (!audioContext) return;\n    let pcm = new Int16Array(event.data);\n    if (pcm.length === 0) {\n        console.warn(\"Received empty PCM data\");\n        return;\n    }\n    if (pcm.length % 2 !== 0) {\n        console.warn(\"Received PCM data with odd length, dropping last sample\");\n        pcm = pcm.slice(0, -1);\n    }\n    \/\/ Convert Int16 PCM to Float32 &#91;-1, 1]\n    let floatBuf = new Float32Array(pcm.length);\n    for (let i = 0; i &lt; pcm.length; i++) {\n        floatBuf&#91;i] = pcm&#91;i] \/ 32768;\n    }\n    \/\/ Limit queue size to prevent memory overflow\n    if (audioQueue.length >= MAX_AUDIO_QUEUE) {\n        audioQueue.shift();\n    }\n    audioQueue.push(floatBuf);\n    scheduleAudioPlayback();\n};<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"715\" src=\"https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1-1024x715.png\" alt=\"\" class=\"wp-image-1338\" srcset=\"https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1-1024x715.png 1024w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1-300x210.png 300w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1-768x537.png 768w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1-1200x838.png 1200w, https:\/\/imuslab.com\/wordpress\/wp-content\/uploads\/2025\/07\/\u5716\u7247-1.png 1264w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>\u53ef\u4ee5\u5b8c\u7f8e\u7684\u5728\u700f\u89bd\u5668\u7528\u53e6\u4e00\u53f0\u7b46\u96fb\u7684\u700f\u89bd\u5668\u770b Youtube<\/figcaption><\/figure>\n\n\n\n<p>\u5c31\u662f\u9019\u6a23\uff0c\u4e00\u500b\u57fa\u65bc WebSocket \u50b3\u8f38 PCM \u5230 front-end \u9032\u884c render \u7684\u7cfb\u7d71\u5c31\u5beb\u597d\u4e86\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u6700\u8fd1\u56e0\u70ba\u5728\u958b\u767c RemdesKVM \uff08\u4e00\u5957\u958b\u6e90\u7684 IP-KVM \u88dd\u7f6e\uff09\uff0c\u6240\u4ee5\u9700\u8981\u60f3\u8fa6\u6cd5\u5728 Linux \u4e0b\u628a USB HDMI capture card \u7684 audio stream \u4e32\u6d41\u5230 Web UI\u3002\u807d\u4e0a\u53bb\u597d\u50cf\u5f88\u7c21\u55ae\uff0c\u4f46\u662f\u60f3\u4e0d\u5230\u5be6\u969b\u4e0a\u505a\u8d77\u4f86\u4e00\u9ede\u4e5f\u4e0d\u5bb9\u6613\uff08 \u70ba\u751a\u9ebc\u5148\u4e0d\u7528 WebRTC\uff1f \u5982\u679c\u4f60\u8ddf\u4e00\u500b\u73fe\u4ee3\u7684 Web Developer \u8b1b\u9019\u529f\u80fd\uff0c\u4ed6\u7b2c\u4e00\u6642\u9593\u56de\u8986\u4f60\u7684\u7576\u7136\u5c31\u662f WebRTC \u4e86\u3002WebRTC \u662f\u4e00\u7a2e\u57fa\u65bc UDP \u7684\u6280\u8853\uff0c\u5bb9\u8a31 Server \u8ddf Client \u4e4b\u9593\u900f\u904e UDP \u9032\u884c real-time communication &amp; streaming\u3002\u90a3\u4e5f\u662f\u56e0\u70ba UDP \u7684\u95dc\u7cfb\uff0c\u6240\u4ee5 packet \u5c31\u662f\u9001\u51fa\u53bb\u5c31\u4e0d\u7406\u4e86\uff0c\u81ea\u7136\u5c31\u4e0d\u6703\u6709\u592a\u5927\u7684 latency \u554f\u984c\u3002\u7136\u800c\u4f7f\u7528 WebRTC \u5354\u8b70\u6703\u51fa\u73fe\u5169\u500b\u554f\u984c\uff1a HTTP \u662f\u57fa\u65bc TCP\uff0c\u56e0\u6b64\u5982\u679c\u672c\u8eab\u4f60\u5df2\u7d93\u6709\u6574\u5957 HTTP proxy \/ routing infrastructure\uff0c\u4f7f\u7528 UDP [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5,111],"tags":[113,112,114,115,33],"class_list":["post-1329","post","type-post","status-publish","format-standard","hentry","category-development-logs","category-remdeskvm","tag-audio","tag-kvm","tag-pcm","tag-streaming","tag-websocket"],"_links":{"self":[{"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/posts\/1329","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/comments?post=1329"}],"version-history":[{"count":10,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/posts\/1329\/revisions"}],"predecessor-version":[{"id":1341,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/posts\/1329\/revisions\/1341"}],"wp:attachment":[{"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/media?parent=1329"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/categories?post=1329"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/imuslab.com\/wordpress\/wp-json\/wp\/v2\/tags?post=1329"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}