如何在Python中实时转换WAV为MP3?
我有一段代码,下面是用来从麦克风获取音频的:
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
2 个回答
1
试试python-audiotools这个工具。我觉得它可以帮助你播放你想要的音频文件。
2
我找到了一种可行的方法,使用了 flask
和 ffmpeg
...
import select
import subprocess
import numpy
from flask import Flask
from flask import Response
app = Flask(__name__)
def get_microphone_audio(num_samples):
# TODO: Add the above microphone code.
audio = numpy.random.rand(num_samples).astype(numpy.float32) * 2 - 1
assert audio.max() <= 1.0
assert audio.min() >= -1.0
assert audio.dtype == numpy.float32
return audio
def response():
pipe = subprocess.Popen(
'ffmpeg -f f32le -acodec pcm_f32le -ar 24000 -ac 1 -i pipe: -f mp3 pipe:'
.split(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
poll = select.poll()
poll.register(pipe.stdout, select.POLLIN)
while True:
pipe.stdin.write(get_synthetic_audio(24000).tobytes())
while poll.poll(0):
yield pipe.stdout.readline()
@app.route('/stream.mp3', methods=['GET'])
def stream():
return Response(
response(),
headers={
# NOTE: Ensure stream is not cached.
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
},
mimetype='audio/mpeg')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, debug=True)
这个解决方案可以进行实时流媒体播放,并且在 Chrome、Firefox 和 Safari 浏览器中都能支持。
这个方案也适用于这个类似的问题:如何根据 Python 中的 NumPy 数组流式传输 MP3 块?