Get the length of an audio file php
If you're using linux / unix and have ffmpeg installed, just do this:
$time = exec("ffmpeg -i " . escapeshellarg($path) . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
list($hms, $milli) = explode('.', $time);
list($hours, $minutes, $seconds) = explode(':', $hms);
$total_seconds = ($hours * 3600) + ($minutes * 60) + $seconds;
PHP has no standard audio support, you'll have to recompile PHP yourself, or you can use a tool to get the information:
You could use ffmpeg. Running ffmpeg as follows:
ffmpeg -i someAudio.mp3
will produce this output:
Input #0, mp3, from 'someAudio.mp3':
Duration: 00:00:34.03, start: 0.000000, bitrate: 127 kb/s
Stream #0.0: Audio: mp3, 48000 Hz, mono, s16, 128 kb/s
now you'll only need a regexp to parse the result.
What kind of audio file? mp3? wav? Anyway you will probably need some specific library. See: http://de.php.net/manual/en/refs.utilspec.audio.php
An improvement of Stephen Fuhry's answer:
/**
* https://stackoverflow.com/a/7135484/470749
* @param string $path
* @return int
*/
function getDurationOfWavInMs($path) {
$time = getDurationOfWav($path);
list($hms, $milli) = explode('.', $time);
list($hours, $minutes, $seconds) = explode(':', $hms);
$totalSeconds = ($hours * 3600) + ($minutes * 60) + $seconds;
return ($totalSeconds * 1000) + $milli;
}
/**
*
* @param string $path
* @return string
*/
function getDurationOfWav($path) {
$cmd = "ffmpeg -i " . escapeshellarg($path) . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//";
return exec($cmd);
}
Thanks, Stephen! This is working well for me (although it is slow for hundreds of files).