简体   繁体   中英

pyav - cannot save stream as mono

I'm trying to use pyav to convert arbitrary audio file to a low quality, mono, wave file.

I almost managed to do it, but it's stereo, and I couldn't find how to make it mono. Furthermore, I think I made some mistake here, as I had to repeat the rate in the output_container.add_stream and in the AudioResampler - it seems redundant, and I can't understand what would happen if those numbers won't match.

My code is:

    import av
    
    input_file = 'some.mp3'
    output_file = 'new.wav'
    
    rate = 22000
    
    output_container = av.open(output_file, 'w')

    # can I tell `output_stream` to just use `resampler`'s info?
    # or, if not, how can I tell it to have only 1 channel?
    output_stream = output_container.add_stream('pcm_u8', rate)  
    
    resampler = av.audio.resampler.AudioResampler('u8p', 'mono', rate)
    
    input_container = av.open(input_file)
    for frame in input_container.decode(audio=0):
        out_frames = resampler.resample(frame)
        for out_frame in out_frames:
            for packet in output_stream.encode(out_frame):
                output_container.mux(packet)
    output_container.close()

And not related to my main question, but any comments regarding my code, or pointing out mistakes, are welcomed. I hardly could find usage examples to use a reference, and PyAV API documentation isn't very detailed...

Searching around in StackOverflow, I found https://stackoverflow.com/a/72386137/1543290 which has:

out_stream = out_container.add_stream(
            'pcm_s16le',
            rate=sample_rate,
            layout='mono'
        )

So, the answer is adding layout='mono' . Sadly, this parameter is not documented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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