java实现任意音频格式转mp3(任意音频格式互转)

需求

最近在集成一款物联网产品获取环境录音功能,从设备那边拿到的录音文件是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.

https://github.com/a-schild/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值