我有以下代码来获取麦克风的音频:
import pyaudio
p = pyaudio.PyAudio()
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 1024*10
RECORD_SECONDS = 10
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
send_via_socket(data) # function to send each frame to remote system
这段代码运行正常。但是每个数据帧的大小为4kb。这意味着发送1秒音频数据需要40kb的互联网数据。 当我把这10个帧(1秒音频)保存到磁盘并使用pdub模块转换为mp3时,只有6kb的数据量。 我该如何在通过套接字发送之前将每个wav帧转换为mp3?(我只需要减小帧的大小以节省网络用量)。 例如:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK) # data =4kb
mp3_frame = wav_to_mp3(data) # mp3_frame should be 1kb or less
send_via_socket(mp3_frame) # function to send each frame to remote system