一.將前臺傳來的serverId(mediaId)拿來,用於請求微信接口,獲取amr文件,並將amr文件保存在相關路徑作爲臨時文件,具體代碼如下:
public static String downloadMediaId(HttpServletRequest request, String mediaId) {
InputStream inputStream = getInputStream(mediaId);
FileOutputStream fileOutputStream = null;
//服務器資源保存路徑
String savePath = "/data/web/uploadfiles/temp/";//你文件的保存路徑
String filename = String.valueOf(System.currentTimeMillis()) + ".amr";//文件名
try {
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
byte[] data = new byte[1024];
int len = 0;
fileOutputStream = new FileOutputStream(savePath + filename);
while ((len = inputStream.read(data)) != -1) {
// 判斷結果是否有錯
if (new String(data).indexOf("errmsg") > -1) {
return null;
//return ;
}
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return savePath+filename;
}
public static InputStream getInputStream(String mediaId) {
InputStream is = null;
try {
String access_token = WeChatUtil.getAccessToken(MemberController.miniProAppId, MemberController.miniProAppSecret, 0);
String URL_DOWNLOAD_TEMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
String url = URL_DOWNLOAD_TEMP_MEDIA.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", mediaId);
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時30秒
http.connect();
// 獲取文件轉化爲byte流
is = http.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
該方法返回保存的amr文件的路徑
二.將amr文件轉爲mp3文件,具體如下:
(1).添加環境:
maven項目添加依賴:
<!--amr文件轉音頻map文件-->
<dependency>
<groupId>com.github.dadiyang</groupId>
<artifactId>jave</artifactId>
<version>1.0.3</version>
</dependency>
jar包:
鏈接:https://pan.baidu.com/s/1YgXbpkxmFbJCupBu2UF61w
提取碼:8sev
(2)具體代碼如下:
/**
* 將微信語音文件保存
* @param serverId
* @throws IOException
*/
@RequestMapping(value="/insertWxVoice")
@ResponseBody
public Object insertWxVoice(@RequestParam("serverId") String serverId,HttpServletRequest request) throws IOException{
Map<String,Object> returnMap = new HashMap<>();
String YearMonthDay = DateUtil.dateFormat(new Date(), "yyyyMMdd");
String sourcePath = WeChatUtil.downloadMediaId(request,serverId);
if(sourcePath==null){
return AppUtil.returnObject(returnMap,Const.ERRORCODE);
}
String targetPath = "/data/web/uploadfiles/voice/"+YearMonthDay+"/"+String.valueOf(System.currentTimeMillis()) + ".mp3";
File temp = new File("/data/web/uploadfiles/voice/"+YearMonthDay+"/");
if(!temp.exists()){//如果文件夾不存在
temp.mkdir();//創建文件夾
}
File source = new File(sourcePath);//源文件
File target = new File(targetPath);//目標文件
if(!source.exists()){
source.createNewFile();
}
if(!target.exists()){
target.createNewFile();
}
//AudioUtils.amrToMp3(source, target);
changeToMp3(sourcePath, targetPath);
returnMap.put("filename", targetPath);
return AppUtil.returnObject(returnMap,Const.SUCCESSCODE);
}
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(new MyFFMpegLoader());
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();
}
}
public class MyFFMpegLoader extends FFMPEGLocator{
@Override
protected String getFFMPEGExecutablePath() {
return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址
}
}
基本流程就是這樣
三.在開發流程中,雖然代碼很快寫完,並且在Windows能很快實現,但是在Linux就遇到了種種問題,現在一一例舉:
(1).java.lang.ClassNotFoundException: it.sauronsoftware.jave.AudioUtils
這個錯誤是因爲環境問題,jar包報錯位置了
(2)Linux it.sauronsoftware.jave.EncoderException: Duration: N/A, bitrate: N/A
這個在Windows和Linux都會有,但是Windows他能生成mp3文件,並且不爲0kb,,二Linux系統是0kb
解決方法:
引入類:
public class MyFFMpegLoader extends FFMPEGLocator{
@Override
protected String getFFMPEGExecutablePath() {
return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址
}
}
自定義修改ffmpeg地址,是其在Linux系統能夠被找到
在changeToMp3()方法中將
Encoder encoder = new Encoder();
改爲
Encoder encoder = new Encoder(new MyFFMpegLoader());
(3).改成之後,但還是有問題:
java.io.IOException: Cannot run program "/data/soft/ffmpeg/ffmpeg", 拒絕訪問
這是因爲這個文件在Linux沒有訪問權限,應該在Linux系統中執行如下命令:
chmod 777 /data/soft/ffmpeg/ffmpeg
/data/soft/ffmpeg/ffmpeg爲文件路徑
四.自此,大功告成,如果大家還有什麼問題的話,也可以在評論區留言