依赖 ffmpeg 所以可以适用于所有 ffmpeg 所支持的文件格式的转换。
- 初始化时判断当前运行环境,将bin目录中对应的 ffmpeg 可执行文件拷贝到临时目录中
- 根据文件类型及配置通过 Runtime.getRuntime().exec(cmd) 执行 ffmpeg 对应的转码命令
<dependency> <groupId>com.github.dadiyang</groupId> <artifactId>jave</artifactId> <version>1.0.0</version> </dependency>
@Slf4j public class VoiceDownload { public static void main(String[] args) throws Exception { System.out.println(FileUtils.getClassPath()); String path1 = "E:\\workSpeace\\target\\93c86b5d67e4443196dbd1ff2b27abe6.amr"; String path2 = "E:\\workSpeace\\target\\93c86b5d67e4443196dbd1ff2b27abe6.mp3"; changeToMp3(path1, path2); } /** * * @param sourcePath 输入amr路径 * @param targetPath 输出MP3路劲 */ public static void changeToMp3(String sourcePath, String targetPath) { System.setProperty("ffmpeg.home", FileUtils.getClassPath() + "ffmpeg"); log.info("ffmpeg.home", FileUtils.getClassPath() + "ffmpeg"); File source = new File(sourcePath); File target = new File(targetPath); AudioAttributes audio = new AudioAttributes(); AmrToMp3Encoder encoder = new AmrToMp3Encoder(); audio.setCodec("libmp3lame"); EncodingAttributes attrs = new EncodingAttributes(); attrs.setFormat("mp3"); attrs.setAudioAttributes(audio); try { encoder.encode(source, target, attrs); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InputFormatException e) { e.printStackTrace(); } catch (EncoderException e) { e.printStackTrace(); } } /** * 判断文件是不是amr格式 * * @param fileName 文件名 * */ public static boolean isAudioAmr(String fileName) { String tmpName = fileName.toLowerCase(); return tmpName.endsWith(".amr"); } private static class AmrToMp3Encoder extends Encoder { @Override protected void processErrorOutput(EncodingAttributes attributes, BufferedReader errorReader, File source, EncoderProgressListener listener) throws EncoderException, IOException { // 屏蔽默认的错误处理 try { String line; while ((line = errorReader.readLine()) != null) { log.debug(line); } } catch (Exception exp) { log.error("file convert error message process failed. ", exp); } } } }