python

python pyaudio 怎样录音

小樊
81
2024-11-25 22:53:58
栏目: 编程语言

要使用Python的PyAudio库进行录音,首先需要安装PyAudio库

pip install pyaudio

接下来,你可以使用以下代码进行录音:

import pyaudio
import wave
import time

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("开始录音...")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("录音完成。")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

这段代码将录制5秒钟的音频,并将其保存到名为"output.wav"的文件中。你可以根据需要调整RECORD_SECONDS变量来更改录音时长。

0
看了该问题的人还看了