Sample song stored on the server

I am developing a site that will allow users to listen to a 30 second sample of a song before making a purchase decision or not. I plan to have all the mp3 files stored under the root folder so that they cannot be directly accessed.

I am trying to figure out if there is a way to make it possible to listen to a 30 second sample of a song using a full mp3 file, or if I have to have an already cut sample mp3 stored on the server. Thank.

+3


source to share


1 answer


The code below should be what you are 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 will probably be preferable because anyone with a basic knowledge of HTML / JS can easily mute the audio file and listen to the entire song. However, the best option would be to trim the song on the server as it saves precious bandwidth. This can be easily done with the sox command line sound editing tool ( 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 lately on a production site and it is very helpful! Most server side frameworks should be able to create a subprocess that can execute commands like this one.

Hope it helps :)

EDIT: After reading Solai's comment, I think the solution he linked to would be the simplest if you are using PHP and want to do it server side. If you want to do it client-side, or are not using PHP, mine will probably be (for now) the way to go.

+1


source







All Articles