rochars / wavefile

Create, read and write wav files according to the specs. :star: :notes: :heart:
MIT License
226 stars 48 forks source link

How to get duration of wav file? #35

Open maxpain opened 1 year ago

wxfred commented 1 year ago

Try this

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

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.

coraxx commented 4 months ago

I calculate it in ms like this:

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