0

I have a function to get .WAV and .MP3 duration. For .Wav it works just fine: 06:31

But with .MP3 it returns nothing.

Can anyone please help me tweak it:

function wavDur($file) {
    $fp = fopen($file, 'r');
    if (fread($fp,4) == 'RIFF') {
        fseek($fp, 20);
        $rawheader = fread($fp, 16);
        $header = unpack('vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits',$rawheader);
        $pos = ftell($fp);
        while (fread($fp,4) != 'data' && !feof($fp)) {
            $pos++;
            fseek($fp,$pos);
        }
        $rawheader = fread($fp, 4);
        $data = unpack('Vdatasize',$rawheader);
        $sec = $data['datasize']/$header['bytespersec'];
        $minutes = intval(($sec / 60) % 60);
        $seconds = intval($sec % 60);
        return str_pad($minutes,2,'0', STR_PAD_LEFT).':'.str_pad($seconds,2,'0', STR_PAD_LEFT);
    }
}




if (preg_match('/[.](wav)|(WAV)|(mp3)|(MP3)$/', $file)) {
    $dur = wavDur($file);
} else {
    $dur = '';
}
medk
  • 9,233
  • 18
  • 57
  • 79
  • 1
    Possible duplicate of [PHP Function to get MP3 duration](https://stackoverflow.com/questions/12053125/php-function-to-get-mp3-duration) – hassan Jul 09 '19 at 09:10
  • 1
    The line `if (fread($fp,4) == 'RIFF')` looks for a WAV file header. If there isn't one (and there won't be if you're examining an MP3 file), then the `waveDur()` function returns nothing. As has already been pointed out, there is already code out there that can give you the length of an MP3 file. There's no point in trying to reinvent this wheel. – r3mainer Jul 09 '19 at 09:25
  • Your text is a lie, as you have no code for MP3, only for WAV. Even the function is clearly named `wavDur`. And your regex is wrong anyway. – AmigoJack Jul 09 '19 at 12:18
  • @AmigoJack `[.]` is valid way of specifying you want exactly the dot character in regex. – Marki555 Dec 08 '21 at 10:20
  • @Marki555 the regex would also match `filename.mp3.zip` and miss `FileName.Mp3` because it lacks basic understanding. The PHP literal should be `'/\\.(wav|mp3)$/i'`. – AmigoJack Dec 08 '21 at 11:33
  • @AmigoJack yes, you are right, the `[.]` (which is itself correct, but not widely used syntax) is part only of the first match alternative (`[.](wav)`) and `$` is part only of the last one (`(MP3)$`), so it has missing `/i` flag and missing parentheses. – Marki555 Dec 09 '21 at 10:37

0 Answers0