Archive

Posts Tagged ‘calculate duration’

PHP code to find Duration of an Audio File

March 18th, 2009 R Arun Raj 2 comments

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.

Videos, Slideshows and Podcasts by Cincopa Wordpress Plugin