Get .wav file length or duration

后端 未结 9 736
暗喜
暗喜 2020-12-04 10:17

I\'m looking for a way to find out the duration of a audio file (.wav) in python. So far i had a look at python wave library, mutagen, pymedi

9条回答
  •  庸人自扰
    2020-12-04 10:50

    The duration is equal to the number of frames divided by the framerate (frames per second):

    import wave
    import contextlib
    fname = '/tmp/test.wav'
    with contextlib.closing(wave.open(fname,'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        duration = frames / float(rate)
        print(duration)
    

    Regarding @edwards' comment, here is some code to produce a 2-channel wave file:

    import math
    import wave
    import struct
    FILENAME = "/tmp/test.wav"
    freq = 440.0
    data_size = 40000
    frate = 1000.0
    amp = 64000.0
    nchannels = 2
    sampwidth = 2
    framerate = int(frate)
    nframes = data_size
    comptype = "NONE"
    compname = "not compressed"
    data = [(math.sin(2 * math.pi * freq * (x / frate)),
            math.cos(2 * math.pi * freq * (x / frate))) for x in range(data_size)]
    try:
        wav_file = wave.open(FILENAME, 'w')
        wav_file.setparams(
            (nchannels, sampwidth, framerate, nframes, comptype, compname))
        for values in data:
            for v in values:
                wav_file.writeframes(struct.pack('h', int(v * amp / 2)))
    finally:
        wav_file.close()
    

    If you play the resultant file in an audio player, you'll find that is 40 seconds in duration. If you run the code above it also computes the duration to be 40 seconds. So I believe the number of frames is not influenced by the number of channels and the formula above is correct.

提交回复
热议问题