import socket
import wave
import pyaudio
import threading

# 音频配置
SAMPLE_RATE = 8000
CHANNELS = 1
SAMPLE_WIDTH = 2  # 16位 = 2字节

class AudioReceiver:
    def __init__(self, host='0.0.0.0', port=12346):
        self.host = host
        self.port = port
        self.running = False
        
        # 初始化PyAudio
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format=self.p.get_format_from_width(SAMPLE_WIDTH),
            channels=CHANNELS,
            rate=SAMPLE_RATE,
            output=True
        )
        
    def start(self):
        # 创建UDP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((self.host, self.port))
        
        self.running = True
        print(f"开始监听 {self.host}:{self.port}")
        
        # 创建录音文件
        self.wave_file = wave.open('received_audio.wav', 'wb')
        self.wave_file.setnchannels(CHANNELS)
        self.wave_file.setsampwidth(SAMPLE_WIDTH)
        self.wave_file.setframerate(SAMPLE_RATE)
        
        while self.running:
            try:
                # 接收数据
                data, addr = self.sock.recvfrom(2048)
                
                # 播放音频
                self.stream.write(data)
                
                # 保存到文件
                self.wave_file.writeframes(data)
                
            except Exception as e:
                print(f"错误: {e}")
                break
                
    def stop(self):
        self.running = False
        self.stream.stop_stream()
        self.stream.close()
        self.p.terminate()
        self.wave_file.close()
        self.sock.close()

def main():
    receiver = AudioReceiver()
    try:
        receiver.start()
    except KeyboardInterrupt:
        print("\n停止接收")
        receiver.stop()

if __name__ == "__main__":
    main() 