Error in live mp3 ffmpeg encoder using python

2019-07-18 07:01发布

问题:

I have a code like below. i want to record sound and convert each wav frame to mp3 format in real time using ffmpeg

import pyaudio,sys
import subprocess
command = ['ffmpeg', '-y','-f','wav' , '-i', '-', '-f', 'mp3', '-']
process = subprocess.Popen(command, stdin=subprocess.PIPE)

p = pyaudio.PyAudio()
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 1024*10
RECORD_SECONDS = 2
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)


mp3 = open("mp3.mp3",'wb')
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    recording_mp3, errordata = process.communicate(data)
    mp3.write(recording_mp3)

Now my code producing error

pipe:: Invalid data found when processing input

My ffmpeg and audio recording working fine. How can i solve this issue ?