ffmpeg-python icon indicating copy to clipboard operation
ffmpeg-python copied to clipboard

read audio stream byte by byte

Open loretoparisi opened this issue 4 years ago • 1 comments

I'm using this approach to load audio stream in bytes chunks

import ffmpeg

def get_url():
    return 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'


if __name__ == '__main__':

    input_opts = {
        'ar': 44100
    }
    output_opts = {}

    stream = (
        ffmpeg
        .input(get_url(), **input_opts)
        .output('pipe:', **output_opts)
        .global_args('-y', '-loglevel', 'panic')
        .run_async(pipe_stdout=True))

    # Read bytes from stream
    while stream.poll() is None:
        in_bytes = stream.stdout.read(1024 * 10)
        print( len(in_bytes) )

but the stdout.read is returning a zero length.

loretoparisi avatar Jul 21 '21 15:07 loretoparisi

def decode_audio(in_filename, **input_kwargs):
    try:
        out = (ffmpeg
            .input(in_filename, **input_kwargs)
            .filter('asetpts', 'PTS-STARTPTS')
            .output('pipe:', format='f32le', acodec='pcm_s32le', ac=1, ar='48k')
            .global_args('-y', '-loglevel', 'panic')
            .overwrite_output()
            .run_async(pipe_stdout=True)
        )
        while True:
            in_bytes = out.stdout.read(4*48000)
            if not in_bytes:
                break
            if len(in_bytes) == 4*48000:
                in_frame = (
                    np
                    .frombuffer(in_bytes, np.float32)
                    .reshape([-1, 48000, 1])
                )
    except ffmpeg.Error as e:
        print(e.stderr, file=sys.stderr)
        sys.exit(1)
    return out

if __name__ == '__main__':
    video_path = 'video_path'
    decode_audio(video_path)

C-Jaewon avatar Jul 21 '22 06:07 C-Jaewon