要使用訊飛的能力,需先注冊訊飛開發平台賬號(訊飛官網參見https://www.xfyun.cn/)。
再創建應用,點擊右上角的控制台 -> 創建新應用:
每個應用都有一個appId,由這個appId關聯對應接口鑒權信息,包括apiKey和apiSecret。比如我創建了一個應用“我的轉寫機” -> 點擊該應用 -> 點擊左邊語音識別里的語音聽寫(流式版):
往下拉,點擊“文檔”,接口說明和demo代碼都在:
進入文檔后拉到底部,點擊鏈接下載demo和音頻:
修改demo里的appId、apiKey和apiSecret、音頻文件所在路徑,就可以直接跑了:
這個接口是websocket協議的,它是把音頻文件一段一段的發送到訊飛做語音識別的,最后識別出來后再返回完整內容,如果你想直接獲取最后的接口,可以用閉鎖阻塞主線程,在websocket關閉時釋放閉鎖,讓主線程繼續:
調用類:
CountDownLatch iatCountDown = new CountDownLatch(1); WebSocket webSocket = client.newWebSocket(request, new WebIATWS(fullFileName, appId, result, iatCountDown, from)); // 阻斷主線程,等待websocket識別完所有語音流 iatCountDown.await();
WebIATWS:
@Override public void onMessage(WebSocket webSocket, String text) { super.onMessage(webSocket, text); System.out.println(text); Gson json = new Gson(); IatResult resp = json.fromJson(text, IatResult.class); if (resp != null) { if (resp.getCode() != 0) { log.error("code=> :{}, error=> :{}, sid= :{}", resp.getCode(), resp.getMessage(), resp.getSid()); return; } if (resp.getData() != null) { if (resp.getData().getResult() != null) { Text te = resp.getData().getResult().getText(); System.out.println(te.toString()); try { decoder.decode(te); log.info("send continue, result: {}", decoder.toString()); } catch (Exception e) { log.error("call onMessage failed, error :{}", e.getMessage()); return; } } if (resp.getData().getStatus() == 2) { //說明數據全部返回完畢,可以關閉連接,釋放資源 log.info("session finish."); dateEnd = new Date(); log.info("cost time: {} ms", dateEnd.getTime() - dateBegin.getTime()); log.info("final result: {}", decoder.toString()); ResultData data = new ResultData(); data.setResult(decoder.toString()); listenResult.setData(data); countDownLatch.countDown(); decoder.discard(); webSocket.close(1000, ""); } } } }