當前位置:
首頁 > 知識 > 一篇文章教會你用Java微信語音開發

一篇文章教會你用Java微信語音開發

一篇文章教會你用Java微信語音開發



-環境、框架

1、伺服器:tomcat8.0.32


2、後台框架:jfinal2.2


3、資料庫:無


4、前端:wechat JS SDK

5、第三方jar:wechat4j、sauronsoftware


一、引入wechat JS SDK


這一步比較簡單,按照微信給的開發文檔一步一步配置就就行,但是步驟比較繁多,利用第三方依賴庫wechat4j,只需幾行代碼即可實現JS JDK的導入。


1、首先是後台Action


public void authWeJs() { String url = getPara("url", null); long timestamp = System.currentTimeMillis() / 1000; String nonceStr = UUID.randomUUID().toString(); String ticket = TokenProxy.jsApiTicket(); String token = TokenProxy.accessToken(); String appid = Config.instance().getAppid(); String sortStr = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; String signature = DigestUtils.sha1Hex(sortStr); setAttr("timestamp", timestamp); setAttr("signature", signature); setAttr("token", token); setAttr("appid", appid); setAttr("nonceStr", nonceStr); System.out.println(signature); System.out.println(sortStr); System.out.println(ticket); renderJson(); }

2、前端JS請求Action獲取接入SDK所需的appid、timestamp、nonceStr、signature


wx.config({ debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來, 若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會列印。 appId: json.appid, // 必填,公眾號的唯一標識 timestamp:json.timestamp , // 必填,生成簽名的時間戳 nonceStr: json.nonceStr, // 必填,生成簽名的隨機串 signature:json.signature,// 必填,簽名,見附錄1 jsApiList: [ checkJsApi , onMenuShareTimeline , onMenuShareAppMessage , onMenuShareQQ , onMenuShareWeibo , hideMenuItems , showMenuItems , hideAllNonBaseMenuItem , showAllNonBaseMenuItem , translateVoice , startRecord , stopRecord , onRecordEnd , playVoice , pauseVoice , stopVoice , uploadVoice , downloadVoice , chooseImage , previewImage , uploadImage , downloadImage , getNetworkType , openLocation , getLocation , hideOptionMenu , showOptionMenu , closeWindow , scanQRCode , chooseWXPay , openProductSpecificView , addCard , chooseCard , openCard ] // 必填,需要使用的JS介面列表,所有JS介面 });


三、錄製語言


// 1、開始錄製wx.startRecord(); //2、停止錄製wx.stopRecord({ success: function (res) { var localId = res.localId; }});//3、上傳錄製好的音頻文件,注意這裡是上傳的微信伺服器,有效期只有三天,到目前位置一直都是使用的微信SDK的API,接下來我們需要上傳到自己的伺服器wx.uploadVoice({ localId: , // 需要上傳的音頻的本地ID,由stopRecord介面獲得 isShowProgressTips: 1, // 默認為1,顯示進度提示 success: function (res) { var serverId = res.serverId; // 返迴音頻的伺服器端ID }});// 4、然而JS JDK文檔裡面並沒有告知如何下載多媒體資源(微信文檔的坑),不過沒有關係第三方依賴庫wechat4j提供了獲取持久化素材的方案,幾行代碼就可以將多媒體資源上傳到自己伺服器,引入wechat4j,只需兩行代碼 MediaFile mediaFile = new MediaFile(); byte[] download = mediaFile.download(media_id);//media_id 就是第三步驟中的serverId// 講byte轉為filepublic static void byte2File(byte[] buf, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }// 第二個坑來了,從微信伺服器下載的音頻文件是amr格式,然而html的audio標籤並不支持amr的播放,這裡我們需要用到第二個三方依賴庫sauronsoftware把amr轉為MP3格式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); try { encoder.encode(source, target, attrs); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InputFormatException e) { e.printStackTrace(); } catch (EncoderException e) { e.printStackTrace(); } }


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 java學習吧 的精彩文章:

SpringMVC從入門到精通之第二章
Java程序員的職業生涯學習 建議
你不知道的java基礎再 回顧

TAG:java學習吧 |