wavefile icon indicating copy to clipboard operation
wavefile copied to clipboard

How to get duration of wav file?

Open maxpain opened this issue 2 years ago • 3 comments

maxpain avatar Mar 29 '23 15:03 maxpain

Try this

wav.fromBuffer(buffer)
const { data, fmt } = wav
const duration = data.chunkSize / fmt.numChannels / fmt.sampleRate / (fmt.bitsPerSample / 8)

wxfred avatar Aug 10 '23 02:08 wxfred

I wasn't able to get the above working for me.

But I was able to use @wxfred 's suggestion to get it working using the following:

    // Where wav is a correctly created WaveFile:
    const duration: number = wav.chunkSize / wav.fmt.numChannels / wav.fmt.sampleRate / (wav.fmt.bitsPerSample / 8)
    // Some debug to validate values are coming back as expected.
    console.log(
        'wav.chunkSize', wav.chunkSize,
        'wav.fmt.numChannels', wav.fmt.numChannels,
        'wav.fmt.sampleRate', wav.fmt.sampleRate,
        'wav.fmt.bitsPerSample', wav.fmt.bitsPerSample
    );

If you save the wave file, on MacOS you can validate the calculated duration of a final output using the built in utility:

afinfo filename.wav | grep duration

I found they were very close, but not exactly the same.

banagale avatar Oct 13 '23 21:10 banagale

I calculate it in ms like this:

var duration = wav.data.chunkSize * 1000 / wav.fmt.blockAlign / wav.fmt.sampleRate / wav.fmt.numChannels;

coraxx avatar Apr 24 '24 21:04 coraxx