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
PHP script to trim MP3 files
Moderator: General Moderators
- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
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');- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
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.
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.
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.If you do so, you will damage all the headers
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.