pythonmp3wavpyav

How to convert mp3 to wav with pyav and python?


I use python and pyav to convert mp3 to wav. My code is below: '''

def mp3_to_wav(mp3_path, wav_path):
 inp = av.open(mp3_path, 'r')
 out = av.open(wav_path, 'w')
 ostream = out.add_stream("pcm_s16le")

    for frame in inp.decode(audio=0):
        frame.pts = None

        for p in ostream.encode(frame):
            out.mux(p)

    for p in ostream.encode(None):
        out.mux(p)

    out.close()
}}

''' but pycharm tell me that Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly Encoder did not produce proper pts, making some up.

How should I do?

Thank you very much.


Solution

  •     
    # noinspection PyUnresolvedReferences
    def to_wav(in_path: str, out_path: str = None, sample_rate: int = 16000) -> str:
        """Arbitrary media files to wav"""
        if out_path is None:
            out_path = os.path.splitext(in_path)[0] + '.wav'
        with av.open(in_path) as in_container:
            in_stream = in_container.streams.audio[0]
            with av.open(out_path, 'w', 'wav') as out_container:
                out_stream = out_container.add_stream(
                    'pcm_s16le',
                    rate=sample_rate,
                    layout='mono'
                )
                for frame in in_container.decode(in_stream):
                    for packet in out_stream.encode(frame):
                        out_container.mux(packet)
    
        return out_path