PHP script to trim MP3 files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
amir
Forum Contributor
Posts: 287
Joined: Sat Oct 07, 2006 4:28 pm

PHP script to trim MP3 files

Post 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
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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');
amir
Forum Contributor
Posts: 287
Joined: Sat Oct 07, 2006 4:28 pm

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
Post Reply