from machine import I2S, Pin
import network
import socket
import time

# 网络配置
SSID = 'waoo2111280'
PASSWORD = 'waoo2111280'
SERVER_IP = '192.168.22.14'
SERVER_PORT = 12346

# I2S配置
sck_pin = Pin(23)  # Serial clock output
ws_pin = Pin(22)   # Word clock output
sd_pin = Pin(21)   # Serial data output

# 配置音频
SAMPLE_RATE = 16000  # 恢复到16000Hz
SAMPLE_BITS = 32     # 改为32位
BUFFER_LENGTH = 1024 # 恢复缓冲区大小

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('正在连接WiFi...')
        wlan.connect(SSID, PASSWORD)
        while not wlan.isconnected():
            time.sleep(1)
    print('WiFi已连接')
    print('IP地址:', wlan.ifconfig()[0])

def init_audio():
    audio_in = I2S(
        0,                         
        sck=sck_pin,
        ws=ws_pin, 
        sd=sd_pin,
        mode=I2S.RX,              
        bits=SAMPLE_BITS,         # 使用32位
        format=I2S.STEREO,        # 改为立体声模式
        rate=SAMPLE_RATE,         
        ibuf=4096                 
    )
    return audio_in

def main():
    # 连接WiFi
    connect_wifi()
    
    # 初始化音频
    audio = init_audio()
    
    # 创建UDP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # 创建音频缓冲区
    audio_buf = bytearray(BUFFER_LENGTH)
    
    print('开始录音和发送...')
    
    try:
        while True:
            # 读取音频数据
            num_read = audio.readinto(audio_buf)
            if num_read > 0:
                # 发送数据到服务器
                sock.sendto(audio_buf[:num_read], (SERVER_IP, SERVER_PORT))
            time.sleep_ms(5)  # 减小延时
                
    except Exception as e:
        print('错误:', e)
    finally:
        audio.deinit()
        sock.close()

if __name__ == '__main__':
    main() 