0

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.

Bill Qu
  • 27
  • 2

1 Answers1

4
    
# 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
foyou
  • 56
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 26 '22 at 04:39
  • How did you know about the `layout='mono'` parameter? I couldn't find it in the docs – Zvika Aug 03 '22 at 07:28
  • I run this answer, and checked with `ffprobe`, and it seems like the output .wav file retains the original frequency, and ignoring `sample_rate`. Maybe an `AudioResampler` is required here? – Zvika Aug 03 '22 at 07:52
  • @Community the code is readable and straight to the point, I don't see how this isn't helpful... I was able to use this almost verbatim to perform the desired task (arbitrary video file -> audio stream -> wav file) – Wes Sep 21 '22 at 17:35