PHP code to find Duration of an Audio File
R Arun Raj | Mar 18, 2009 | Comments 3
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.
Filed Under: PHP • Programming
About the Author: me : yeay its me arun




My friend on Facebook shared this link and I’m not dissapointed at all that I came here.
This is quite a hot information. I think I’ll share it on Digg.
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..