溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)的百度語(yǔ)音識(shí)別功能示例

發(fā)布時(shí)間:2020-08-28 10:57:28 來(lái)源:腳本之家 閱讀:170 作者:eclipse_c 欄目:編程語(yǔ)言

本文實(shí)例講述了Java實(shí)現(xiàn)的百度語(yǔ)音識(shí)別功能。分享給大家供大家參考,具體如下:

SDK以及示例代碼下載地址: http://yuyin.baidu.com/sdk

最近一直在搞java,就選擇了java工程。將代碼拷過(guò)去。同時(shí)復(fù)制文件“test.pcm”到工程目錄下。就基本上可以了。

注:test.pcm是語(yǔ)音文件,可以用audacity軟件打開(kāi),選擇 文件->導(dǎo)入->裸數(shù)據(jù)。 設(shè)置采樣率為8000Hz。點(diǎn)擊播放就能聽(tīng)見(jiàn)聲音了。

這個(gè)時(shí)候程序跑起來(lái)還有問(wèn)題,需要將apiKey 以及secretKey填寫(xiě)上。這兩個(gè)值是你申請(qǐng)應(yīng)用對(duì)應(yīng)的分配好的。

cuid填本機(jī)mac地址就可以了,這個(gè)值我試過(guò)好像無(wú)所謂沒(méi)啥要求。

程序能跑起來(lái),并且按照正常返回識(shí)別的語(yǔ)音結(jié)果。但是返回結(jié)果的編碼為GBK,所以漢字顯示為亂碼,需要對(duì)其進(jìn)行一次轉(zhuǎn)碼。轉(zhuǎn)碼的代碼是我自己加上去的。

下面貼代碼:

package com.baidu.speech.serviceapi;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.xml.bind.DatatypeConverter;
import org.json.JSONObject;
public class Sample {
  private static final String serverURL = "http://vop.baidu.com/server_api";
  private static String token = "";
  private static final String testFileName = "test.pcm"; // 百度語(yǔ)音提供技術(shù)支持
  //put your own params here
  // 下面3個(gè)值要填寫(xiě)自己申請(qǐng)的app對(duì)應(yīng)的值
  private static final String apiKey = "";
  private static final String secretKey = "";
  private static final String cuid = "";
  public static void main(String[] args) throws Exception {
    getToken();
    method1();
    method2();
  }
  private static void getToken() throws Exception {
    String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +
      "&client_id=" + apiKey + "&client_secret=" + secretKey;
    HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();
    token = new JSONObject(printResponse(conn)).getString("access_token");
  }
  private static void method1() throws Exception {
    File pcmFile = new File(testFileName);
    HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();
    // construct params
    JSONObject params = new JSONObject();
    params.put("format", "pcm");
    params.put("rate", 8000);
    params.put("channel", "1");
    params.put("token", token);
    params.put("lan", "zh");
    params.put("cuid", cuid);
    params.put("len", pcmFile.length());
    params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));
    // add request header
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    // send request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params.toString());
    wr.flush();
    wr.close();
    printResponse(conn);
  }
  private static void method2() throws Exception {
    File pcmFile = new File(testFileName);
    HttpURLConnection conn = (HttpURLConnection) new URL(serverURL
        + "?cuid=" + cuid + "&token=" + token).openConnection();
    // add request header
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "audio/pcm; rate=8000");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    // send request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.write(loadFile(pcmFile));
    wr.flush();
    wr.close();
    System.out.println(getUtf8String(printResponse(conn)));
  }
  private static String printResponse(HttpURLConnection conn) throws Exception {
    if (conn.getResponseCode() != 200) {
      // request error
     System.out.println("conn.getResponseCode() = " + conn.getResponseCode());
      return "";
    }
    InputStream is = conn.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = rd.readLine()) != null) {
      response.append(line);
      response.append('\r');
    }
    rd.close();
    System.out.println(new JSONObject(response.toString()).toString(4));
    return response.toString();
  }
  private static byte[] loadFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
    long length = file.length();
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
        && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += numRead;
    }
    if (offset < bytes.length) {
      is.close();
      throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    return bytes;
  }
  // GBK編碼轉(zhuǎn)為UTF-8
  private static String getUtf8String(String s) throws UnsupportedEncodingException
  {
   StringBuffer sb = new StringBuffer();
   sb.append(s);
   String xmlString = "";
   String xmlUtf8 = "";
 xmlString = new String(sb.toString().getBytes("GBK"));
 xmlUtf8 = URLEncoder.encode(xmlString , "GBK");
   return URLDecoder.decode(xmlUtf8, "UTF-8");
  }
}

更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI