依賴 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); } } } }