10000 How to use FFMPEG-PYTHON in continuous stream of audio chunks? · Issue #855 · kkroening/ffmpeg-python · GitHub
[go: up one dir, main page]

Skip to content
How to use FFMPEG-PYTHON in continuous stream of audio chunks?  #855
Open
@ThiruRJST

Description

@ThiruRJST

I get OPUS-WEBM audio chunks from web-browser which I need convert it to PCM16 format. I tried using ffmpeg-python with the continuous chunks of data. The code actually converts the first chunk of the stream which contains the EBML header and throws an error when the subsequent chunks with no headers arrive like: EBML header not found, Invalid data.

Is there anyother way to handle the headerless chunks coming from a websocket chunks with ffmpeg-python or any other alternative to ffmpeg-python that handles continuous stream of audio data as chunks

import subprocess

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()



Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0