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 .

unpack(‘vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits’,$rawheader);

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.. !!

$size_in_bytes/bytespersec.

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’,
$rawheader);
$sec = ceil($size_in_bytes/$header['bytespersec']);
return $sec;

}

Have fun.

About

me : yeay its me arun

Tagged with: , ,
Posted in PHP, Programming
3 Comments » for 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..

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>