PHP code to find Duration of an Audio File

Here is the PHP function to calculated duration of “wav” or “GSM” files

First we open file using fopen. After we calculate the size of that file (inbytes) using filesize().

Then we unpack the audio File .


This will return following array

Array (
[type] => 1
[channels] => 2
[samplerate] => 44100
[bytespersec] => 176400
[alignment] => 4 [bits] => 16 )

from this array we get bytepersec.

Now it is very easy to find out the duration.. !!


Code is here.

public static function getDuration($file) {

$fp = fopen($file, ‘r’);
$size_in_bytes = filesize($file);
fseek($fp, 20);
$rawheader = fread($fp, 16);
$header = unpack(‘vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits’,
$sec = ceil($size_in_bytes/$header[‘bytespersec’]);
return $sec;


Have fun.


me : yeay its me arun

Tagged with: , ,
4 comments on “PHP code to find Duration of an Audio File
  1. Ex Boyfriend says:

    My friend on Facebook shared this link and I’m not dissapointed at all that I came here.

  2. Limerp says:

    This is quite a hot information. I think I’ll share it on Digg.

  3. Ujjawal says:

    Arun, its really a nice code.
    It helped me to serve a client with app. that gets the length of uploaded audio or video files.

    Thank you..

  4. Sheetal says:

    Code is not working… wrong duration

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.