简体   繁体   English

如何使用python实时将wav转换为mp3?

[英]how to convert wav to mp3 in live using python?

I have code like what is shown below to get audio from microphone:我有如下所示的代码来从麦克风获取音频:

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

This code is working fine.这段代码工作正常。 However each data frame has a size of 4kb.然而,每个数据帧的大小为 4kb。 That means 40kb of internet data is needed to send 1 sec of audio data.这意味着需要 40kb 的互联网数据才能发送 1 秒的音频数据。 It's only 6kb of data When I saved the 10 frames (1 second audio) to disc and convert it to mp3 using the pdub module.当我将 10 帧(1 秒音频)保存到光盘并使用 pdub 模块将其转换为 mp3 时,它只有 6kb 的数据。 How can I convert each wav frame to mp3 before sending via socket?如何在通过套接字发送之前将每个 wav 帧转换为 mp3? (I just need to reduce the size of the frame to save network usage). (我只需要减小框架的大小以节省网络使用量)。 For example:例如:

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

try python-audiotools .试试python-audiotools I think it will help you stream the audio file that you want.我认为它会帮助您流式传输所需的音频文件。

I was able to figure out a working approach using flask and ffmpeg ...我能够找出使用flaskffmpeg的工作方法......

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)

This solution allows for live streaming and is supported in Chrome, Firefox, and Safari.此解决方案允许实时流式传输,并在 Chrome、Firefox 和 Safari 中受支持。

This solution also worked for this similar question: How to stream MP3 chunks given a NumPy array in Python?这个解决方案也适用于这个类似的问题: How to stream MP3 chunks given an NumPy array in Python?

I have code like what is shown below to get audio from microphone:我有如下所示的代码,可从麦克风获取音频:

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

This code is working fine.这段代码工作正常。 However each data frame has a size of 4kb.但是,每个数据帧的大小为4kb。 That means 40kb of internet data is needed to send 1 sec of audio data.这意味着需要40kb的互联网数据才能发送1秒的音频数据。 It's only 6kb of data When I saved the 10 frames (1 second audio) to disc and convert it to mp3 using the pdub module.当我将10帧(1秒音频)保存到光盘上并使用pdub模块将其转换为mp3时,仅6kb的数据。 How can I convert each wav frame to mp3 before sending via socket?在通过套接字发送之前,如何将每个wav帧转换为mp3? (I just need to reduce the size of the frame to save network usage). (我只需要减小框架的大小即可节省网络使用量)。 For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM