How to “Trim” an Audio File in Java, C# or PHP (Fo

2019-05-23 20:46发布

问题:

I'm trying to create a web application which requires this feature:

Suppose I have a .mp3 file, I want to select/upload this file, and then, make a new file of it from 0:15 to 0:30 (example), and then save as new .mp3/.wav.

As it's supposed to go on web, would be preferrable in PHP, but as I highly doubt it's possible, Java(Applets) or C#(ASP.NET) are acceptable and highly appreciated.

Thanks in advance.

回答1:

The best way to do this is with FFMPEG. There is a PHP extension for it, but I've generally found that it is easiest to just call it with exec().

ffmpeg -ss 00:00:15 -t 15 -i yourfile.mp3 -acodec copy outputfile.mp3

More info here: http://www.catswhocode.com/blog/19-ffmpeg-commands-for-all-needs



回答2:

If you want to do it in Java, you could use the AudioSamples class from JAudio.


// read the file into an AudioSamples object
AudioSamples as = new AudioSamples(new File("originalFile.mp3"),"",false);

// get the audio from 15 to 30 seconds
double[][] samples = as.getSamplesChannelSegregated(15.0, 30.0);

// discard the rest of the samples
as.setSamples(samples);

// write the samples to a .wav file
as.saveAudio(new File("newAudioFileName.wav"), true, AudioFileFormat.Type.WAVE, false);