CogletESP-CogletESP/scripts/audio_debug_server.py
Rdzleo c63b35a0e7
Some checks failed
Build Boards / Determine variants to build (push) Successful in 6m26s
Build Boards / Build ${{ matrix.name }} (push) Failing after 6m43s
1、第一次提交项目,项目初始化;
2、修改了RP2040的代码,使其在没有安装摄像头的情况下也可以左右转动眼球和左右转动身体;
3、增加了一些中文注释的说明;
2026-04-09 14:22:24 +08:00

55 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import socket
import wave
import argparse
'''
Create a UDP socket and bind it to the server's IP:8000.
Listen for incoming messages and print them to the console.
Save the audio to a WAV file.
'''
def main(samplerate, channels):
# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', 8000))
# Create WAV file with parameters
filename = f"{samplerate}_{channels}.wav"
wav_file = wave.open(filename, "wb")
wav_file.setnchannels(channels) # channels parameter
wav_file.setsampwidth(2) # 2 bytes per sample (16-bit)
wav_file.setframerate(samplerate) # samplerate parameter
print(f"Start saving audio from 0.0.0.0:8000 to {filename}...")
try:
while True:
# Receive a message from the client
message, address = server_socket.recvfrom(8000)
# Write PCM data to WAV file
wav_file.writeframes(message)
# Print length of the message
print(f"Received {len(message)} bytes from {address}")
except KeyboardInterrupt:
print("\nStopping recording...")
finally:
# Close files and socket
wav_file.close()
server_socket.close()
print(f"WAV file '{filename}' saved successfully")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='UDP音频数据接收器保存为WAV文件')
parser.add_argument('--samplerate', '-s', type=int, default=16000,
help='采样率 (默认: 16000)')
parser.add_argument('--channels', '-c', type=int, default=2,
help='声道数 (默认: 2)')
args = parser.parse_args()
main(args.samplerate, args.channels)