Read wav header and calculate duration


/ Published in: PHP
Save to your folder(s)

Use unpack() to decode header information. Return duration in format mm:ss


Copy this code and paste it in your HTML
  1. function wavDur($file) {
  2. $fp = fopen($file, 'r');
  3. if (fread($fp,4) == "RIFF") {
  4. fseek($fp, 20);
  5. $rawheader = fread($fp, 16);
  6. $header = unpack('vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits',$rawheader);
  7. $pos = ftell($fp);
  8. while (fread($fp,4) != "data" && !feof($fp)) {
  9. $pos++;
  10. fseek($fp,$pos);
  11. }
  12. $rawheader = fread($fp, 4);
  13. $data = unpack('Vdatasize',$rawheader);
  14. $sec = $data[datasize]/$header[bytespersec];
  15. $minutes = intval(($sec / 60) % 60);
  16. $seconds = intval($sec % 60);
  17. return str_pad($minutes,2,"0", STR_PAD_LEFT).":".str_pad($seconds,2,"0", STR_PAD_LEFT);
  18. }
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.