如何實現HTML5語音識別功能?老熊程式設計師2019-09-07 20:53:57

技術上主要分為兩個部分:語音獲取、語音識別;

一、語音獲取

在html上增加錄音按鈕,使用 HZRecorder。js,呼叫裝置的錄音功能,(注意:手機端瀏覽器需要有ssl證書(即網址協議為https)才能呼叫錄音,有人說打包了就可以,沒有ssl證書,打包了也會呼叫失敗)

前端:

<!DOCTYPE html>

後臺:在UploadVideoServlet中處理上傳和呼叫語音識別程式碼。

@WebServlet(“/UploadVideoServlet”)

public class UploadVideoServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public UploadVideoServlet() {

super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response。getWriter()。append(“Served at: ”)。append(request。getContextPath());

this。doPost(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// 訊息提示

String message = “”;

try {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

List list = upload。parseRequest(request);

for (FileItem item : list) {

// 呼叫語音識別方法

// Sample。main(item。get()); //百度

WebIAT。main(item。get()); //科大訊飛

message = “檔案上傳成功!”;

}

} catch (Exception e) {

message = “檔案上傳失敗!”;

e。printStackTrace();

}

}

}

二、語音識別:使用科大訊飛或者百度提供的api實現。

如何實現HTML5語音識別功能?一木窗20202019-09-07 07:22:42

HTML5之語音識別例項程式碼說明:1)x-webkit-speech:語音識別支援屬性2)lang:設定語言種類,比如漢語:lang=“ch-CN”3) x-webkit-grammar :語音輸入語法比如: x-webkit-grammar=“bUIltin:search”使得語音輸入的內容儘量靠近搜尋內容,去除多餘的字元,例如“的、啦”等4) onwebkitspeechchange :語音輸入事件,當語音改變時觸發比如:onwebkitspeechchange=“foo()” ,當停止語音時,會觸發js中的foo()函式此時,需要寫相應的JavaScript函式foo()