【Java】百度语音识别REST API使用方法不需要集成SDK的方法

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

获得Token

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

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");  
  }  

现在假设语音文件为testFileName =test.pcm,保存在一个文件中,该文件可以有很多方法获得,比如在Android中调用录音相关的API,下面代码展示了如何通过Http网络请求获得识别结果。

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

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("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();  
  
      printResponse(conn);  
  }  
下面展示了该demo的全部代码,开发者可以填入自己的KEY尝试使用。
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";  
    //put your own params here  
    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("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();  
  
        printResponse(conn);  
    }  
  
    private static void printResponse(HttpURLConnection conn) throws Exception {  
        if (conn.getResponseCode() != 200) {  
            // request error  
        }  
        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));  
    }  
  
    private static byte[] loadFile(File file) throws IOException {  
        InputStream is = new FileInputStream(file);  
  
        long length = file.length();r  
        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;  
    }  
}  


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值