一 問題起因
在做微信客服開發時,遇到了一個問題 就是微信語音的格式是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方法 看有沒有檔案生成,并且看能不能用