Search code examples
javascriptaudiobufferdurationpcm

Evaluate duration from raw audio array data of sound fragment


How to evaluate duration of sound fragment from raw array data?

I get raw data from microphone and I know the sample rate and the number of channels. I need mathematical formula to calculate the duration of this audio fragment.

I found out this:

1000 * bytesLength / 4 / rate_hz

But I think it's wrong.


Solution

  • Salient factors balancing off quality against resource demands for raw audio in PCM format :

     Attribute     Typical Values
    ____________  _________________
    bit_depth     16 bits per sample (8 bits per byte)        ... higher the better
    num_channels  2 for stereo (or 1 for mono), lets use stereo
    sample_rate   44100 samples per second (CD quality audio) ... higher the better
    

    This formula expresses relationship between above variables :

    storage_in_bytes / second == num_channels * sample_rate * bit_depth / 8
    

    solving for seconds : (here is the equation you ask for)

    duration in seconds = storage_in_bytes/(num_channels * sample_rate * (bit_depth/8))
    

    plugging in using above variables we need to supply either storage_in_bytes or duration in seconds, so if

    storage_in_bytes = 2 mb = 2097152 bytes
    

    then we get

    duration = 2097152/(2 * 44100 * (16/8)) = 11.89 seconds