使用微信录音将amr转为mp3
一.將前臺(tái)傳來的serverId(mediaId)拿來,用于請求微信接口,獲取amr文件,并將amr文件保存在相關(guān)路徑作為臨時(shí)文件,具體代碼如下:
public static String downloadMediaId(HttpServletRequest request, String mediaId) {InputStream inputStream = getInputStream(mediaId);FileOutputStream fileOutputStream = null;//服務(wù)器資源保存路徑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) {// 判斷結(jié)果是否有錯(cuò)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");// 連接超時(shí)30秒System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時(shí)30秒http.connect();// 獲取文件轉(zhuǎn)化為byte流is = http.getInputStream();} catch (Exception e) {e.printStackTrace();}return is;}該方法返回保存的amr文件的路徑
二.將amr文件轉(zhuǎn)為mp3文件,具體如下:
(1).添加環(huán)境:
maven項(xiàng)目添加依賴:
<!--amr文件轉(zhuǎn)音頻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")@ResponseBodypublic 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();//創(chuàng)建文件夾 }File source = new File(sourcePath);//源文件File target = new File(targetPath);//目標(biāo)文件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{@Overrideprotected String getFFMPEGExecutablePath() {return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址} }基本流程就是這樣
三.在開發(fā)流程中,雖然代碼很快寫完,并且在Windows能很快實(shí)現(xiàn),但是在Linux就遇到了種種問題,現(xiàn)在一一例舉:
(1).java.lang.ClassNotFoundException: it.sauronsoftware.jave.AudioUtils
這個(gè)錯(cuò)誤是因?yàn)榄h(huán)境問題,jar包報(bào)錯(cuò)位置了
(2)Linux it.sauronsoftware.jave.EncoderException: Duration: N/A, bitrate: N/A
這個(gè)在Windows和Linux都會(huì)有,但是Windows他能生成mp3文件,并且不為0kb,,二Linux系統(tǒng)是0kb
解決方法:
引入類:
public class MyFFMpegLoader extends FFMPEGLocator{@Overrideprotected String getFFMPEGExecutablePath() {return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址} }?自定義修改ffmpeg地址,是其在Linux系統(tǒng)能夠被找到
在changeToMp3()方法中將
Encoder encoder = new Encoder();
改為
Encoder encoder = new Encoder(new MyFFMpegLoader());
(3).改成之后,但還是有問題:
java.io.IOException:?Cannot run program "/data/soft/ffmpeg/ffmpeg", 拒絕訪問
這是因?yàn)檫@個(gè)文件在Linux沒有訪問權(quán)限,應(yīng)該在Linux系統(tǒng)中執(zhí)行如下命令:
chmod 777 /data/soft/ffmpeg/ffmpeg
/data/soft/ffmpeg/ffmpeg為文件路徑
四.自此,大功告成,如果大家還有什么問題的話,也可以在評(píng)論區(qū)留言
總結(jié)
以上是生活随笔為你收集整理的使用微信录音将amr转为mp3的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 构建规则格网进行体积计算
- 下一篇: Docker CI: 安装 SonarQ