一 問題起因
在做微信客服開發時,遇到了一個問題 就是微信語音的格式是amr格式 一般的瀏覽器還解析不了這類語音文件,必須要將它轉換為mp3格式;
二 問題解決
我在網上找了一些資料,說的不全,在此總結補充一下;
1.需要下載第三方jar 下載JAVE 1.0.2
http://www.sauronsoftware.it/projects/jave/download.php
2.引入pom依賴
<dependency> <groupId>it.sauronsoftware.jave</groupId> <artifactId>jave</artifactId> <version>1.0.2</version> </dependency>
3.mvn 打包項目 會報錯 然后你把 jave-1.0.2.jar放到maven的依賴倉庫中
三 代碼
package com.hmzj.callcenterim.utils; import it.sauronsoftware.jave.*; import lombok.extern.slf4j.Slf4j; import java.io.*; @Slf4j public class ChangeAudioFormat { public static void main(String[] args) throws Exception { String path1 = "C:\\Users\\pc\\Desktop\\amr.js-master\\assets\\female.amr"; String path2 = "C:\\Users\\pc\\Desktop\\amr.js-master\\assets\\female.mp3"; changeToMp3(path1, path2); } /** * windows版 執行此方法 * * @param sourcePath * @param targetPath */ public static void changeToMp3(String sourcePath, String targetPath) { File source = new File(sourcePath); File target = new File(targetPath); AudioAttributes audio = new AudioAttributes(); Encoder encoder = new Encoder(); audio.setCodec("libmp3lame"); EncodingAttributes attrs = new EncodingAttributes(); attrs.setFormat("mp3"); attrs.setAudioAttributes(audio); log.debug("正在轉換微信語音amr"); try { encoder.encode(source, target, attrs); log.debug("正在轉換微信語音"); } catch (IllegalArgumentException e) { e.printStackTrace(); log.debug(e.toString()); } catch (InputFormatException e) { e.printStackTrace(); log.debug(e.toString()); } catch (EncoderException e) { e.printStackTrace(); log.debug(e.toString()); } } /** * linux執行此方法 * * @param localPath * @param targetFilePath */ public static void amrToMP3Linux(String localPath, String targetFilePath){ log.debug("執行命令開始"); String command = "ffmpeg -i "+localPath+" "+targetFilePath; log.debug("the command is : "+command); Runtime runtime = Runtime.getRuntime(); try { Process proc = runtime.exec(command); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) sb.append(line); int exitVal = proc.waitFor(); log.debug("the exitVal is : "+exitVal); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { log.debug("ffmpeg exec cmd Exception " + e.toString()); } log.debug("執行命令結束"); log.debug(runtime.toString()); } }
注意windows上可使用 changeToMp3 這個方法 但linux上此方法不行 必須執行 amrToMP3Linux 此方法
四 在linux上安裝ffmpeg
下載站點:http://ffmpeg.org/download.html
因為我的服務器是64位 所以下載解壓這個
利用ftp將解壓后的文件夾放到服務器上
賦予權限
# chmod +x /usr/local/ffmpeg-4.0.2-64bit-static/ffmpeg
配置環境變量
vi etc/profile
export FFMPEG_HOME=/usr/local/ffmpeg-4.0.2-64bit-static/
export PATH=$FFMPEG_HOME:$PATH
保存並退出
source etc/profile
然后在服務器上執行上面的linux方法 看有沒有文件生成,並且看能不能用