python pyaudio collects voice data

python pyaudio collects voice data

pyaudio installation method:

pip install pyaudio

If this doesn't work, you can try:

pip install pipwin
pipwin install pyaudio

code show as below:

import pyaudio
import wave

RESPEAKER_RATE = 44100  # 采样率,每秒钟对声音信号的采样次数
RESPEAKER_CHANNELS = 1  # 通道数,一般单声道、双声道
RESPEAKER_WIDTH = 2  # 带宽 (量化位数),单个采样点的位数,2 表示每个采样点使用 16 位表示
CHUNK = 1024  # 数据块大小,每次从音频流中读取的数据量大小
RECORD_SECONDS = 10  # 录制时长
RESPEAKER_INDEX = 0  # 输入设备索引
WAVE_OUTPUT_FILENAME = "output.wav"  # 输出文件名

# 调用 pyaudio,打开语音流
p = pyaudio.PyAudio()
stream = p.open(
    rate=RESPEAKER_RATE,
    format=p.get_format_from_width(RESPEAKER_WIDTH),
    channels=RESPEAKER_CHANNELS,
    input=True,
    input_device_index=RESPEAKER_INDEX
)

print("* recording")

frames = []

# 将获取的数据写入语音流,并计算时间
# RESPEAKER_RATE / CHUNK * RECORD_SECONDS 计算了录制音频所需的数据块个数
# int 对于浮点数 会向下取整
# 向上取整:math.ceil()
# 向下取整:math.floor()
for i in range(0, int(RESPEAKER_RATE / CHUNK * RECORD_SECONDS)):
    # exception_on_overflow=False 当输入缓冲区没有足够的数据,避免引发异常,返回空字符串
    data = stream.read(CHUNK, exception_on_overflow=False)
    frames.append(data)

print("* done recording")

# 停止语音流,数据写入文件,释放资源
stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
wf.setnchannels(RESPEAKER_CHANNELS)
wf.setsampwidth(p.get_sample_size(p.get_format_from_width(RESPEAKER_WIDTH)))
wf.setframerate(RESPEAKER_RATE)
wf.writeframes(b"".join(frames))
wf.close()

Then an output.wav audio file will be generated
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43327597/article/details/134795373