import pyaudio
import wave

mic_index = 1       # 改这里：0 / 1 / None
RATE = 48000        # 改这里
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1        # 设备1不行再试2
SECONDS = 5

p = pyaudio.PyAudio()
stream = None

try:
    print(f"Opening mic index={mic_index}, rate={RATE}, channels={CHANNELS}")

    kwargs = {
        "format": FORMAT,
        "channels": CHANNELS,
        "rate": RATE,
        "input": True,
        "frames_per_buffer": CHUNK,
    }
    if mic_index is not None:
        kwargs["input_device_index"] = mic_index

    stream = p.open(**kwargs)

    print("recording...")
    frames = []
    for _ in range(int(RATE / CHUNK * SECONDS)):
        data = stream.read(CHUNK, exception_on_overflow=False)
        frames.append(data)

    print("done")

    out_file = f"test_mic_{mic_index}_{RATE}_{CHANNELS}ch.wav"
    with wave.open(out_file, "wb") as wf:
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b"".join(frames))

    print(f"saved: {out_file}")

except Exception as e:
    print("ERROR:", e)

finally:
    if stream is not None:
        stream.stop_stream()
        stream.close()
    p.terminate()
