Page 1 of 1

PHP script to trim MP3 files

Posted: Fri Oct 13, 2006 4:46 am
by amir
Hello!
I cannot find a php script to truncate MP3 file on a server. When a user uploads MP3 file to the server, I have to create its trimmed version for preview (10-15 sec). Since MP3 is an audio compresssed file, I cannot just cut its part and have to make mp3 decoding-encoding. Is that correct?

Please, advise the simplest way of doing this.

Thank you

Posted: Fri Oct 13, 2006 4:59 am
by Ollie Saunders
You'll need to work out the kbps of the mp3 file to determine how many bytes you should truncate. You may be right about not being able to cut is but there's one good way to find out:

Code: Select all

$inputFile = file_get_contents($filename = 'song.mp3');
$kbps = 128; $seconds = 10;
$outputFile = substr($inputFile, 0, $kbps / 8 * $seconds);
file_put_contents($outputFile, $filename . '.trunc');

Posted: Fri Oct 13, 2006 5:11 am
by amir
Thanks!

How can you cut a compressed file right away? If you do so, you will damage all the headers. It is the same as cut zip file in two. a correct way would be to decode mp3, trim it and decode again.

Posted: Fri Oct 13, 2006 5:19 am
by Ollie Saunders
I'm not sure sure how well it will do, the last part of the file may be corrupted, it may not. However it won't fail completely because an mp3 is not a zip. It is not indexed in the way standard compression is. An mp3 is split into many segments (I'm not sure how big) and each is independent. Ideally we would probably like to make the cut at a segment end.
If you do so, you will damage all the headers
Headers appear at the start (the head). If you were to remove these the file wouldn't work absolutely. Thinking about it there are probaby headers containing information about the length of the file that you would need to update. So perhaps my code suggestion isn't so great.

Have a look about for PHP mp3 libraries. Don't go with anything that has to decode the mp3 to a wav modify that and re-encode because that'll be very very slow and you'll lose quality.