需求
最近在集成一款物联网产品获取环境录音功能,从设备那边拿到的录音文件是amr格式的,小程序那边会有兼容性问题,所以我们需要转换为mp3格式。
Java实现
这里我们使用JAVE2
库来实现音频格式转码,项目管理工具使用的Maven
The JAVE2 (Java Audio Video Encoder) library is Java wrapper on the ffmpeg project. Developers can take take advantage of JAVE2 to transcode audio and video files from a format to another. In example you can transcode an AVI file to a MPEG one, you can change a DivX video stream into a (youtube like) Flash FLV one, you can convert a WAV audio file to a MP3 or a Ogg Vorbis one, you can separate and transcode audio and video tracks, you can resize videos, changing their sizes and proportions and so on.
Many other formats, containers and operations are supported by JAVE2.
在项目pom.xml
文件里添加依赖
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>3.4.0</version>
</dependency>
<!-- Linux 环境 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-nativebin-linux64</artifactId>
<version>3.4.0</version>
</dependency>
<!-- MacOS 环境 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-nativebin-osx64</artifactId>
<version>3.4.0</version>
</dependency>
<!-- Win64 环境 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-nativebin-win64</artifactId>
<version>3.4.0</version>
</dependency>
tips: 上面的环境依赖按需添加
代码:将音频转换为mp3格式
/**
* 将音频转换为mp3
*
* @param source 源音频文件
* @param target 输出的音频文件
*/
public static void audioConvert2Mp3(File source, File target)
{
try
{
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
audio.setBitRate(128000);
audio.setChannels(2);
audio.setSamplingRate(44100);
EncodingAttributes attrs = new EncodingAttributes();
attrs.setOutputFormat("mp3");
attrs.setAudioAttributes(audio);
Encoder encoder = new Encoder();
encoder.encode(new MultimediaObject(source), target, attrs);
}
catch(Exception ex)
{
log.error(ex.getMessage(), ex);
}
}
更多高级用法
详见 github