python进行实时音频录制
pyaudio库
使用pyaudio打开一个stream
import pyaudio
import audioop
p=pyaudio.PyAudio()
# Config
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3
DEVICE_INDEX = 0
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index = DEVICE_INDEX)
audioop库
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK,
exception_on_overflow=False) #16进制
print(data)
rms = audioop.rms(data, 2)
print([audioop.getsample(data, 2, i) for i in range(len(data) // 2)]) #映射到2**-15 - 2**15-1. width=2意思是2个字节16个Byte
print(rms) #均方根
stream.stop_stream()
stream.close()
p.terminate()
# 随便摘取一例结果
b'\xf0\xff\xf0\xff\xec\xff\xec\xff\xed\xff\xed\xff\xe8\xff\xe7\xff\xe7\xff\xe8\xff\xea\xff\xe9\xff\xe6\xff\xe6\xff\xe8\xff\xe8\xff\xea\xff\xea\xff\xe9\xff\xe9\xff\xea\xff\xea\xff #后面太长了省略
[-16, -16, -20, -20, -19, -19, -24, -25, -25, -24, -22, -23, -26, -26, -24, -24, -22, -22, -23, -23, -22, -22, -21, -21, -23, -22, -26, -27, -26, -26, -32, -32, -40, -40, -38, -39, -40, -40, -39, -39, -34, -35, -35, -34, -35, -36, -35, -35, -33, -32, -34, -34, -37, -37, -39, -38, -46, -46, -50, -49, -51, -51, -56, -56, -52, -52, -48, -48, -46, -46, -