3

I'm designing a site that would allow users to listen to a 30 second sample of a song before deciding whether or not to purchase it. I plan on having all the mp3s stored below the root folder so that they cannot be directly accessed.

What I'm trying to figure out though, is whether there is a way to allow a 30 second sample of the song to be heard by utilizing the full mp3 file, or if I'll have to have an already cut sample mp3 stored on the server as well. Thanks.

user3817799
  • 147
  • 1
  • 7
  • http://stackoverflow.com/questions/1404969/automatically-trimming-an-mp3-in-php Check this out. Is this helpful? – Sundar Jul 29 '15 at 04:45

1 Answers1

1

The code below should be what you're looking for:

HTML:

<audio src="song.mp3" id="song">

Javascript:

var song = document.getElementById('song');
song.play(); //Start playing sound
setTimeout(function(){song.pause(), 30000}; //Pause the song after 30,000 millisends(30 seconds);

or

var song = document.getElementById('song');
song.play(); //start playing sound
setTimeout(function(){song.src="";}, 30000); //Instead of pausing the song, you remove the source file of the song which basically stops the sound

The second option would probably be preferable because anyone with basic HTML/JS knowledge could easily unpause the audio file and listen to the entire song. However, your best option would be to trim the song on the server because it saves precious bandwidth. It can easily be done with the command line audio editing tool sox(http://sox.sourceforge.net/) using the following syntax

sox <originalFile> <newFile> trim <startTime> <duration>

Example:

sox input.wav output.wav trim 0 00:35

I have been using sox on a production site lately and it's very useful! Most server-side frameworks have to ability to spawn a subprocess that can run commands such as this one.

Hope this helps :)

EDIT: After reading the comment, I think the linked solution would be the simplest solution if you're using PHP and want to do it server-side. If you want to do it client-side or you're not using PHP, my solution would probably be the way to go.

Cameron
  • 58
  • 2
  • 6