如何在连续的音频片段中使用 FFMPEG-Python?
class OpusToPCMConverter: def init(self): # Start an ffmpeg process that keeps running, converting chunks of Opus WebM to PCM self.ffmpeg_process = subprocess.Popen( [ "ffmpeg", "-f", "webm", # Input format "-i", "pipe:0", # Input from stdin (we will feed chunks here) "-f", "s16le", # Output format (PCM 16-bit little endian) "-acodec", "pcm_s16le", # PCM codec "-ar", "16000", # Audio sample rate (16kHz as an example) "-ac", "1", # Mono channel (you can adjust if needed) "pipe:1" # Output to stdout (we will read the PCM output from here) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=10**6 # Buffer size to handle streamed data efficiently )
def convert_chunk(self, opus_chunk):
"""
Convert a chunk of WebM/Opus data to PCM.
Parameters:
opus_chunk (bytes): The chunk of WebM/Opus data.
Returns:
bytes: The converted PCM data, or None if an error occurred.
"""
# Feed the chunk into the ffmpeg process
self.ffmpeg_process.stdin.write(opus_chunk)
self.ffmpeg_process.stdin.flush()
# Read the output PCM data
pcm_data = self.ffmpeg_process.stdout.read(4096) # Read in chunks of PCM
return pcm_data
def close(self):
# Close the ffmpeg process properly
self.ffmpeg_process.stdin.close()
self.ffmpeg_process.stdout.close()
self.ffmpeg_process.stderr.close()
self.ffmpeg_process.terminate()内容来源: kkroening/ffmpeg-python