zoukankan      html  css  js  c++  java
  • 百度语音识别REST API用法(含JAVA代码)——不须要集成SDK的方法

    版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/zpf8861/article/details/32329457

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

    本文代码为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('
    ');
            }
            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;
        }
    }





查看全文
  • 相关阅读:
    使用Project Linker 2012实现多个项目中代码文件
    使用的开放源码Scryber库动态生成PDF文件
    破解Excel 密码保护
    入围51CTO 2009年度“最受读者欢迎的IT图书作者”评选
    谈谈分布式事务之二:基于DTC的分布式事务管理模型[下篇]
    WCF 技术剖析之三十三:你是否了解WCF事务框架体系内部的工作机制?[下篇]
    事件(Event),绝大多数内存泄漏(Memory Leak)的元凶[下篇] (提供Source Code下载)
    如何实现对上下文(Context)数据的统一管理 [提供源代码下载]
    WCF技术剖析之二十七: 如何将一个服务发布成WSDL[基于HTTPGET的实现](提供模拟程序)
    Enterprise Library深入解析与灵活应用(9):个人觉得比较严重的关于CachingCallHandler的Bug
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10515408.html
  • Copyright © 2011-2022 走看看