简体   繁体   English

pyav - 无法将 stream 保存为 mono

[英]pyav - cannot save stream as mono

I'm trying to use pyav to convert arbitrary audio file to a low quality, mono, wave file.我正在尝试使用pyav将任意音频文件转换为低质量的 mono 波形文件。

I almost managed to do it, but it's stereo, and I couldn't find how to make it mono.我几乎设法做到了,但它是立体声的,我找不到如何制作 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.此外,我认为我在这里犯了一些错误,因为我不得不在output_container.add_streamAudioResampler中重复rate - 这似乎是多余的,我无法理解如果这些数字不匹配会发生什么。

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...我几乎找不到使用示例来使用参考,而且 PyAV API 文档不是很详细......

Searching around in StackOverflow, I found https://stackoverflow.com/a/72386137/1543290 which has:在 StackOverflow 中搜索,我发现https://stackoverflow.com/a/72386137/1543290具有:

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

So, the answer is adding layout='mono' .所以,答案是添加layout='mono' Sadly, this parameter is not documented.遗憾的是,此参数未记录在案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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