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.