分享

百度语音识别REST API使用方法(含JAVA代码)——不需要集成SDK的方法

 昵称18098338 2014-07-09

上一篇文章http://blog.csdn.net/zpf8861/article/details/32322089已经介绍了百度语音识别REST API的使用步骤和功能介绍,这篇文章主要通过一个实例代码来展示如何使用该API。

本文代码为JAVA版,可以用于Android应用开发中,下面介绍其中重要的代码。

获得Token

其中apiKey和secretKey是从百度开放平台获得的,获得方法参看上一篇文章。

  1. private static void getToken() throws Exception {  
  2.       String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +   
  3.           "&client_id=" + apiKey + "&client_secret=" + secretKey;  
  4.       HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();  
  5.       token = new JSONObject(printResponse(conn)).getString("access_token");  
  6.   }  
现在假设语音文件为testFileName =test.pcm,保存在一个文件中,该文件可以有很多方法获得,比如在Android中调用录音相关的API,下面代码展示了如何通过Http网络请求获得识别结果。

Http连接采用Post方式,首先需要设定参数,然后上传本地的语音数据。

  1. private static void method1() throws Exception {  
  2.        File pcmFile = new File(testFileName);  
  3.        HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();  
  4.   
  5.        // construct params  
  6.        JSONObject params = new JSONObject();  
  7.        params.put("format""pcm");  
  8.        params.put("rate"8000);  
  9.        params.put("channel""1");  
  10.        params.put("token", token);  
  11.        params.put("cuid", cuid);  
  12.        params.put("len", pcmFile.length());  
  13.        params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));  
  14.   
  15.        // add request header  
  16.        conn.setRequestMethod("POST");  
  17.        conn.setRequestProperty("Content-Type""application/json; charset=utf-8");  
  18.   
  19.        conn.setDoInput(true);  
  20.        conn.setDoOutput(true);  
  21.   
  22.        // send request  
  23.        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  24.        wr.writeBytes(params.toString());  
  25.        wr.flush();  
  26.        wr.close();  
  27.   
  28.        printResponse(conn);  
  29.    }  
然后是获得响应的方法,具体处理识别结果
  1. private static void method2() throws Exception {  
  2.       File pcmFile = new File(testFileName);  
  3.       HttpURLConnection conn = (HttpURLConnection) new URL(serverURL  
  4.               + "?cuid=" + cuid + "&token=" + token).openConnection();  
  5.   
  6.       // add request header  
  7.       conn.setRequestMethod("POST");  
  8.       conn.setRequestProperty("Content-Type""audio/pcm; rate=8000");  
  9.   
  10.       conn.setDoInput(true);  
  11.       conn.setDoOutput(true);  
  12.   
  13.       // send request  
  14.       DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  15.       wr.write(loadFile(pcmFile));  
  16.       wr.flush();  
  17.       wr.close();  
  18.   
  19.       printResponse(conn);  
  20.   }  

下面展示了该demo的全部代码,开发者可以填入自己的KEY尝试使用。

  1. public class Sample {  
  2.   
  3.     private static final String serverURL = "http://vop.baidu.com/server_api";  
  4.     private static String token = "";  
  5.     private static final String testFileName = "test.pcm";  
  6.     //put your own params here  
  7.     private static final String apiKey = "";  
  8.     private static final String secretKey = "";  
  9.     private static final String cuid = "";  
  10.   
  11.     public static void main(String[] args) throws Exception {  
  12.         getToken();  
  13.         method1();  
  14.         method2();  
  15.     }  
  16.   
  17.     private static void getToken() throws Exception {  
  18.         String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +   
  19.             "&client_id=" + apiKey + "&client_secret=" + secretKey;  
  20.         HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();  
  21.         token = new JSONObject(printResponse(conn)).getString("access_token");  
  22.     }  
  23.   
  24.     private static void method1() throws Exception {  
  25.         File pcmFile = new File(testFileName);  
  26.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();  
  27.   
  28.         // construct params  
  29.         JSONObject params = new JSONObject();  
  30.         params.put("format""pcm");  
  31.         params.put("rate"8000);  
  32.         params.put("channel""1");  
  33.         params.put("token", token);  
  34.         params.put("cuid", cuid);  
  35.         params.put("len", pcmFile.length());  
  36.         params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));  
  37.   
  38.         // add request header  
  39.         conn.setRequestMethod("POST");  
  40.         conn.setRequestProperty("Content-Type""application/json; charset=utf-8");  
  41.   
  42.         conn.setDoInput(true);  
  43.         conn.setDoOutput(true);  
  44.   
  45.         // send request  
  46.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  47.         wr.writeBytes(params.toString());  
  48.         wr.flush();  
  49.         wr.close();  
  50.   
  51.         printResponse(conn);  
  52.     }  
  53.   
  54.     private static void method2() throws Exception {  
  55.         File pcmFile = new File(testFileName);  
  56.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL  
  57.                 + "?cuid=" + cuid + "&token=" + token).openConnection();  
  58.   
  59.         // add request header  
  60.         conn.setRequestMethod("POST");  
  61.         conn.setRequestProperty("Content-Type""audio/pcm; rate=8000");  
  62.   
  63.         conn.setDoInput(true);  
  64.         conn.setDoOutput(true);  
  65.   
  66.         // send request  
  67.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  68.         wr.write(loadFile(pcmFile));  
  69.         wr.flush();  
  70.         wr.close();  
  71.   
  72.         printResponse(conn);  
  73.     }  
  74.   
  75.     private static void printResponse(HttpURLConnection conn) throws Exception {  
  76.         if (conn.getResponseCode() != 200) {  
  77.             // request error  
  78.         }  
  79.         InputStream is = conn.getInputStream();  
  80.         BufferedReader rd = new BufferedReader(new InputStreamReader(is));  
  81.         String line;  
  82.         StringBuffer response = new StringBuffer();  
  83.         while ((line = rd.readLine()) != null) {  
  84.             response.append(line);  
  85.             response.append('\r');  
  86.         }  
  87.         rd.close();  
  88.         System.out.println(new JSONObject(response.toString()).toString(4));  
  89.     }  
  90.   
  91.     private static byte[] loadFile(File file) throws IOException {  
  92.         InputStream is = new FileInputStream(file);  
  93.   
  94.         long length = file.length();r  
  95.         byte[] bytes = new byte[(int) length];  
  96.   
  97.         int offset = 0;  
  98.         int numRead = 0;  
  99.         while (offset < bytes.length  
  100.                 && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {  
  101.             offset += numRead;  
  102.         }  
  103.   
  104.         if (offset < bytes.length) {  
  105.             is.close();  
  106.             throw new IOException("Could not completely read file " + file.getName());  
  107.         }  
  108.   
  109.         is.close();  
  110.         return bytes;  
  111.     }  
  112. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多