Use FFmpeg in Java to convert AMR-formatted voice to MP3 format

Source: Internet
Author: User
Tags temporary file storage



FFmpeg is a very powerful audio and video processing tool, the official website is: http://ffmpeg.org/.



Because FFmpeg does not have the same files on Windows and on Linux systems (you do not need to install FFmpeg on Windows, you only need to download the Windows version of FFmpeg. Linux requires the user to install ffmpeg---> Reference link: http://linux.it.net.cn/e/Linuxit/2014/0828/3980.html)






The most recent project is a requirement to convert the audio files in the AMR format from Android to MP3 format and then play them on the web.



I. How Windows systems and Linux systems are handled



1, first on the Windows system to solve. There are 2 scenarios, one is to use the Jave.jar Toolkit, the other is to unzip the downloaded version of Windows FFmpeg directly, and then import the Ffmpeg.exe file in the bin directory into the project (or read the local ffmpeg.exe execution file directly using code) )。



1.1. Using the Jave.jar tool kit



http://mfan.iteye.com/blog/2032454



1.2. execute files using Ffmpeg.exe



1.2.1, use local ffmpeg.exe to execute files, get directly through file






1.2.2, import the Ffmpeg.exe executable file into the project, via URL url = thread.currentthread (). Getcontextclassloader (). GetResource ("ffmpeg/ windows/"); To get









1.3. Use FFmpeg on Linux server to convert AMR to mp3



1.3.1, first to install the FFmpeg tool on the Linux server, the installation method is shown above






Second, the Utils tool class (Code specific implementation)





 
* *
* Create By yxl on 2018/6/5
* /
public class AmrToMP3Utils {
private static Logger logger =Logger.getLogger(AmrToMP3Utils.class);
* *
*Convert AMR file input to MP3 format
* @param file
* @return
* /
public static InputStream amrToMP3(MultipartFile file) {
String ffmpegPath = getLinuxOrWindowsFfmpegPath();
Runtime runtime = Runtime.getRuntime();
Try {
String filePath = copyFile(file.getInputStream(), file.getOriginalFilename());
String substring = filePath.substring(0, filePath.lastIndexOf("."));
String mp3FilePath = substring + ".mp3";
//Execute ffmpeg file, change AMR format to MP3
//Filepath ----- > address of AMR file in temporary folder
//Mp3 filepath ----- > the address of the converted MP3 file
Process P = runtime.exec (ffmpegpath + "ffmpeg - I" + filepath + "" + mp3filepath); / / execute ffmpeg.exe, with the address of ffmpeg.exe in the front, the address of the file to be converted in the middle, and the address of the converted file in the back. -I is the conversion mode, which means that it can be encoded and decoded. The MP3 encoding mode is libmp3 lame
//Release process
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
P.waitFor ();
File mp3File = new File(mp3FilePath);
InputStream fileInputStream = new FileInputStream(mp3File);
//The input stream should be closed where the method is called (after use), and the corresponding files under the temporary folder should be deleted
/*File amrFile = new File(filePath);
File mp3File = new File(mp3FilePath);
if (amrFile.exists()) {
boolean delete = amrFile.delete();
System. Out. Println ("delete source file:" + delete);
}
if (mp3File.exists()) {
boolean delete = mp3File.delete();
System. Out. Println ("delete MP3 file:" + delete);
* *
return fileInputStream;
} catch (Exception e) {
e.printStackTrace();
} finally {
runtime.freeMemory();
}
Return null;
}
* *
*Transfer AMR file input to MP3 format
*Input stream of @ param InputStream AMR file (it can also be other file streams)
*@ param filename filename (including suffix)
* @return
* /
public static InputStream amrToMP3(InputStream inputStream, String fileName) {
String ffmpegPath = getLinuxOrWindowsFfmpegPath();
Runtime runtime = Runtime.getRuntime();
Try {
String filePath = copyFile(inputStream, fileName);
String substring = filePath.substring(0, filePath.lastIndexOf("."));
String mp3FilePath = substring + ".mp3";
//Execute ffmpeg file, change AMR format to MP3
//Filepath ----- > address of AMR file in temporary folder
//Mp3 filepath ----- > the address of the converted MP3 file
Process P = runtime.exec (ffmpeg path + "ffmpeg - I" + "" + filepath + "" + mp3filepath); / / execute ffmpeg.exe, with the address of ffmpeg.exe in the front, the address of the file to be converted in the middle, and the address of the converted file in the back. -I is the conversion mode, which means that it can be encoded and decoded. The MP3 encoding mode is libmp3 lame
//Release process
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
P.waitFor ();
File file = new File(mp3FilePath);
InputStream fileInputStream = new FileInputStream(file);
//The input stream should be closed where the method is called (after use), and the corresponding files under the temporary folder should be deleted
/*File amrFile = new File(filePath);
File mp3File = new File(mp3FilePath);
if (amrFile.exists()) {
boolean delete = amrFile.delete();
System. Out. Println ("delete source file:" + delete);
}
if (mp3File.exists()) {
boolean delete = mp3File.delete();
System. Out. Println ("delete MP3 file:" + delete);
* *
return fileInputStream;
} catch (Exception e) {
e.printStackTrace();
} finally {
runtime.freeMemory();
}
Return null;
}
* *
*Transfer the AMR audio file input by the user to the audio file and store it in the temporary folder
*@ param InputStream
*@ param filename file name
*@ return AMR temporary file storage address
* @throws IOException
* /
private static String copyFile(InputStream inputStream, String fileName) throws IOException {
Properties props = System.getProperties();
String filepath = props. Getproperty ("user. Home") + file. Separator + "mp3tempfile"; / / create a temporary directory
File dir = new File(filePath);
if (!dir.exists()) {
Dir.mkdir ();
}
String outPutFile = dir + File.separator + fileName;
OutputStream outputStream = new FileOutputStream(outPutFile);
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
return outPutFile;
}
* *
*Judge whether the system is windows or Linux and splice ffmpegpath
* @return
* /
private static String getLinuxOrWindowsFfmpegPath() {
String ffmpegPath = "";
String osName = System.getProperties().getProperty("os.name");
if (osName.toLowerCase().indexOf("linux") >= 0) {
ffmpegPath = "";
} else {
URL url = Thread.currentThread().getContextClassLoader().getResource("ffmpeg/windows/");
if (url != null) {
ffmpegPath = url.getFile();
}
}
return ffmpegPath;
}
}














Use FFmpeg in Java to convert AMR-formatted voice to MP3 format


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.