基于java的百度语音识别示例



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


最近一直在搞java,就选择了java工程。将代码拷过去。同时复制文件“test.pcm”到工程目录下。就基本上可以了。

注:test.pcm是语音文件,可以用audacity软件打开,选择 文件->导入->裸数据。 设置采样率为8000Hz。点击播放就能听见声音了。

这个时候程序跑起来还有问题,需要将apiKey 以及secretKey填写上。这两个值是你申请应用对应的分配好的。

cuid填本机mac地址就可以了,这个值我试过好像无所谓没啥要求。

程序能跑起来,并且按照正常返回识别的语音结果。但是返回结果的编码为GBK,所以汉字显示为乱码,需要对其进行一次转码。转码的代码是我自己加上去的。

下面贴代码:

[java]  view plain  copy
  1. package com.baidu.speech.serviceapi;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.DataOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.InputStreamReader;  
  10. import java.io.UnsupportedEncodingException;  
  11. import java.net.HttpURLConnection;  
  12. import java.net.URL;  
  13. import java.net.URLDecoder;  
  14. import java.net.URLEncoder;  
  15.   
  16. import javax.xml.bind.DatatypeConverter;  
  17.   
  18. import org.json.JSONObject;  
  19.   
  20. public class Sample {  
  21.   
  22.     private static final String serverURL = "http://vop.baidu.com/server_api";  
  23.     private static String token = "";  
  24.     private static final String testFileName = "test.pcm"// 百度语音提供技术支持  
  25.     //put your own params here  
  26.     // 下面3个值要填写自己申请的app对应的值  
  27.     private static final String apiKey = "";  
  28.     private static final String secretKey = "";  
  29.     private static final String cuid = "";  
  30.   
  31.     public static void main(String[] args) throws Exception {  
  32.         getToken();  
  33.         method1();  
  34.         method2();  
  35.     }  
  36.   
  37.     private static void getToken() throws Exception {  
  38.         String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +   
  39.             "&client_id=" + apiKey + "&client_secret=" + secretKey;  
  40.         HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();  
  41.         token = new JSONObject(printResponse(conn)).getString("access_token");  
  42.     }  
  43.   
  44.     private static void method1() throws Exception {  
  45.         File pcmFile = new File(testFileName);  
  46.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();  
  47.   
  48.         // construct params  
  49.         JSONObject params = new JSONObject();  
  50.         params.put("format""pcm");  
  51.         params.put("rate"8000);  
  52.         params.put("channel""1");  
  53.         params.put("token", token);  
  54.         params.put("lan""zh");  
  55.         params.put("cuid", cuid);  
  56.         params.put("len", pcmFile.length());  
  57.         params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));  
  58.   
  59.         // add request header  
  60.         conn.setRequestMethod("POST");  
  61.         conn.setRequestProperty("Content-Type""application/json; charset=utf-8");  
  62.   
  63.         conn.setDoInput(true);  
  64.         conn.setDoOutput(true);  
  65.   
  66.         // send request  
  67.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  68.         wr.writeBytes(params.toString());  
  69.         wr.flush();  
  70.         wr.close();  
  71.   
  72.         printResponse(conn);  
  73.     }  
  74.   
  75.     private static void method2() throws Exception {  
  76.         File pcmFile = new File(testFileName);  
  77.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL  
  78.                 + "?cuid=" + cuid + "&token=" + token).openConnection();  
  79.   
  80.         // add request header  
  81.         conn.setRequestMethod("POST");  
  82.         conn.setRequestProperty("Content-Type""audio/pcm; rate=8000");  
  83.   
  84.         conn.setDoInput(true);  
  85.         conn.setDoOutput(true);  
  86.   
  87.         // send request  
  88.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  89.         wr.write(loadFile(pcmFile));  
  90.         wr.flush();  
  91.         wr.close();  
  92.   
  93.         System.out.println(getUtf8String(printResponse(conn)));  
  94.     }  
  95.   
  96.     private static String printResponse(HttpURLConnection conn) throws Exception {  
  97.         if (conn.getResponseCode() != 200) {  
  98.             // request error  
  99.             System.out.println("conn.getResponseCode() = " + conn.getResponseCode());  
  100.             return "";  
  101.         }  
  102.         InputStream is = conn.getInputStream();  
  103.         BufferedReader rd = new BufferedReader(new InputStreamReader(is));  
  104.         String line;  
  105.         StringBuffer response = new StringBuffer();  
  106.         while ((line = rd.readLine()) != null) {  
  107.             response.append(line);  
  108.             response.append('\r');  
  109.         }  
  110.         rd.close();  
  111.         System.out.println(new JSONObject(response.toString()).toString(4));  
  112.         return response.toString();  
  113.     }  
  114.   
  115.     private static byte[] loadFile(File file) throws IOException {  
  116.         InputStream is = new FileInputStream(file);  
  117.   
  118.         long length = file.length();  
  119.         byte[] bytes = new byte[(int) length];  
  120.   
  121.         int offset = 0;  
  122.         int numRead = 0;  
  123.         while (offset < bytes.length  
  124.                 && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {  
  125.             offset += numRead;  
  126.         }  
  127.   
  128.         if (offset < bytes.length) {  
  129.             is.close();  
  130.             throw new IOException("Could not completely read file " + file.getName());  
  131.         }  
  132.   
  133.         is.close();  
  134.         return bytes;  
  135.     }  
  136.       
  137.     // GBK编码转为UTF-8  
  138.     private static String getUtf8String(String s) throws UnsupportedEncodingException  
  139.     {  
  140.         StringBuffer sb = new StringBuffer();  
  141.         sb.append(s);  
  142.         String xmlString = "";  
  143.         String xmlUtf8 = "";  
  144.         xmlString = new String(sb.toString().getBytes("GBK"));  
  145.         xmlUtf8 = URLEncoder.encode(xmlString , "GBK");  
  146.           
  147.         return URLDecoder.decode(xmlUtf8, "UTF-8");  
  148.     }  
  149. }  

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


最近一直在搞java,就选择了java工程。将代码拷过去。同时复制文件“test.pcm”到工程目录下。就基本上可以了。

注:test.pcm是语音文件,可以用audacity软件打开,选择 文件->导入->裸数据。 设置采样率为8000Hz。点击播放就能听见声音了。

这个时候程序跑起来还有问题,需要将apiKey 以及secretKey填写上。这两个值是你申请应用对应的分配好的。

cuid填本机mac地址就可以了,这个值我试过好像无所谓没啥要求。

程序能跑起来,并且按照正常返回识别的语音结果。但是返回结果的编码为GBK,所以汉字显示为乱码,需要对其进行一次转码。转码的代码是我自己加上去的。

下面贴代码:

[java]  view plain  copy
  1. package com.baidu.speech.serviceapi;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.DataOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.InputStreamReader;  
  10. import java.io.UnsupportedEncodingException;  
  11. import java.net.HttpURLConnection;  
  12. import java.net.URL;  
  13. import java.net.URLDecoder;  
  14. import java.net.URLEncoder;  
  15.   
  16. import javax.xml.bind.DatatypeConverter;  
  17.   
  18. import org.json.JSONObject;  
  19.   
  20. public class Sample {  
  21.   
  22.     private static final String serverURL = "http://vop.baidu.com/server_api";  
  23.     private static String token = "";  
  24.     private static final String testFileName = "test.pcm"// 百度语音提供技术支持  
  25.     //put your own params here  
  26.     // 下面3个值要填写自己申请的app对应的值  
  27.     private static final String apiKey = "";  
  28.     private static final String secretKey = "";  
  29.     private static final String cuid = "";  
  30.   
  31.     public static void main(String[] args) throws Exception {  
  32.         getToken();  
  33.         method1();  
  34.         method2();  
  35.     }  
  36.   
  37.     private static void getToken() throws Exception {  
  38.         String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +   
  39.             "&client_id=" + apiKey + "&client_secret=" + secretKey;  
  40.         HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();  
  41.         token = new JSONObject(printResponse(conn)).getString("access_token");  
  42.     }  
  43.   
  44.     private static void method1() throws Exception {  
  45.         File pcmFile = new File(testFileName);  
  46.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();  
  47.   
  48.         // construct params  
  49.         JSONObject params = new JSONObject();  
  50.         params.put("format""pcm");  
  51.         params.put("rate"8000);  
  52.         params.put("channel""1");  
  53.         params.put("token", token);  
  54.         params.put("lan""zh");  
  55.         params.put("cuid", cuid);  
  56.         params.put("len", pcmFile.length());  
  57.         params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));  
  58.   
  59.         // add request header  
  60.         conn.setRequestMethod("POST");  
  61.         conn.setRequestProperty("Content-Type""application/json; charset=utf-8");  
  62.   
  63.         conn.setDoInput(true);  
  64.         conn.setDoOutput(true);  
  65.   
  66.         // send request  
  67.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  68.         wr.writeBytes(params.toString());  
  69.         wr.flush();  
  70.         wr.close();  
  71.   
  72.         printResponse(conn);  
  73.     }  
  74.   
  75.     private static void method2() throws Exception {  
  76.         File pcmFile = new File(testFileName);  
  77.         HttpURLConnection conn = (HttpURLConnection) new URL(serverURL  
  78.                 + "?cuid=" + cuid + "&token=" + token).openConnection();  
  79.   
  80.         // add request header  
  81.         conn.setRequestMethod("POST");  
  82.         conn.setRequestProperty("Content-Type""audio/pcm; rate=8000");  
  83.   
  84.         conn.setDoInput(true);  
  85.         conn.setDoOutput(true);  
  86.   
  87.         // send request  
  88.         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());  
  89.         wr.write(loadFile(pcmFile));  
  90.         wr.flush();  
  91.         wr.close();  
  92.   
  93.         System.out.println(getUtf8String(printResponse(conn)));  
  94.     }  
  95.   
  96.     private static String printResponse(HttpURLConnection conn) throws Exception {  
  97.         if (conn.getResponseCode() != 200) {  
  98.             // request error  
  99.             System.out.println("conn.getResponseCode() = " + conn.getResponseCode());  
  100.             return "";  
  101.         }  
  102.         InputStream is = conn.getInputStream();  
  103.         BufferedReader rd = new BufferedReader(new InputStreamReader(is));  
  104.         String line;  
  105.         StringBuffer response = new StringBuffer();  
  106.         while ((line = rd.readLine()) != null) {  
  107.             response.append(line);  
  108.             response.append('\r');  
  109.         }  
  110.         rd.close();  
  111.         System.out.println(new JSONObject(response.toString()).toString(4));  
  112.         return response.toString();  
  113.     }  
  114.   
  115.     private static byte[] loadFile(File file) throws IOException {  
  116.         InputStream is = new FileInputStream(file);  
  117.   
  118.         long length = file.length();  
  119.         byte[] bytes = new byte[(int) length];  
  120.   
  121.         int offset = 0;  
  122.         int numRead = 0;  
  123.         while (offset < bytes.length  
  124.                 && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {  
  125.             offset += numRead;  
  126.         }  
  127.   
  128.         if (offset < bytes.length) {  
  129.             is.close();  
  130.             throw new IOException("Could not completely read file " + file.getName());  
  131.         }  
  132.   
  133.         is.close();  
  134.         return bytes;  
  135.     }  
  136.       
  137.     // GBK编码转为UTF-8  
  138.     private static String getUtf8String(String s) throws UnsupportedEncodingException  
  139.     {  
  140.         StringBuffer sb = new StringBuffer();  
  141.         sb.append(s);  
  142.         String xmlString = "";  
  143.         String xmlUtf8 = "";  
  144.         xmlString = new String(sb.toString().getBytes("GBK"));  
  145.         xmlUtf8 = URLEncoder.encode(xmlString , "GBK");  
  146.           
  147.         return URLDecoder.decode(xmlUtf8, "UTF-8");  
  148.     }  
  149. }  

你可能感兴趣的:(JAVA)