【发布时间】:2020-09-05 20:08:34
【问题描述】:
我正在寻找直接从麦克风编码 mp3 文件而不保存到中间 wav 文件的方法。有大量用于保存到 wav 文件的示例以及大量用于将 wav 文件转换为 mp3 的示例。但是我没有找到直接从麦克风保存 mp3 的方法。例如,我正在使用网上找到的以下示例录制到 wav 文件。
我希望获得有关如何将frames 列表(pyaudio 流读取)直接转换为 mp3 的建议。或者,通过 ffmpeg 将 pyaudio 麦克风输入直接流式传输到 mp3,而不用读取数据填充列表/数组。非常感谢!
import pyaudio
import wave
# the file name output you want to record into
filename = "recorded.wav"
# set the chunk size of 1024 samples
chunk = 1024
# sample format
FORMAT = pyaudio.paInt16
# mono, change to 2 if you want stereo
channels = 1
# 44100 samples per second
sample_rate = 44100
record_seconds = 5
# initialize PyAudio object
p = pyaudio.PyAudio()
# open stream object as input & output
stream = p.open(format=FORMAT,
channels=channels,
rate=sample_rate,
input=True,
output=True,
frames_per_buffer=chunk)
frames = []
print("Recording...")
for i in range(int(44100 / chunk * record_seconds)):
data = stream.read(chunk)
frames.append(data)
print("Finished recording.")
# stop and close stream
stream.stop_stream()
stream.close()
# terminate pyaudio object
p.terminate()
# save audio file
# open the file in 'write bytes' mode
wf = wave.open(filename, "wb")
# set the channels
wf.setnchannels(channels)
# set the sample format
wf.setsampwidth(p.get_sample_size(FORMAT))
# set the sample rate
wf.setframerate(sample_rate)
# write the frames as bytes
wf.writeframes(b"".join(frames))
# close the file
wf.close()
【问题讨论】:
-
我应该说我在 python 3.8.1 和 windows10 上
标签: python ffmpeg mp3 pyaudio lame