ARS百度语音识别简单Demo

1.请求方式为http://服务器的IP地址:8080/BaiduYYInterface/BaiduASRInterface?filename=文件名称

public void init(ServletConfig config) throws ServletException {
        super.init(config);
        //这个方法只执行一次,实现单例模式
        final String APP_ID = config.getInitParameter("APP_ID");
        final String API_KEY = config.getInitParameter("API_KEY");
        final String SECRET_KEY = config.getInitParameter("SECRET_KEY");
        // 初始化一个AipSpeech
        client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选:设置log4j日志输出格式,若不设置,则使用默认配置
        //也可以直接通过jvm启动参数设置此环境变量
        //System.setProperty("aip.log4j.conf", "log4j.properties");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletConfig config = this.getServletConfig();
        String FileDir = config.getInitParameter("FileDir")==null?"":config.getInitParameter("FileDir");
        //获取请求参数
        request.setCharacterEncoding("utf-8");
        String filename = request.getParameter("filename");
        JSONObject res = new JSONObject();
        try {
            if(filename!=null && filename.length()>0){
                // 调用接口
                String path =FileDir + File.separatorChar + filename;
                if (new File(path).exists()) {
                    //byte[] data = Util.readFileByBytes(path);
                    res = client.asr(path, "pcm", 16000, null);
                }else{
                    res.put("err_no", 2000);
                    res.put("err_msg", "文件不存在,请确定文件目录以及文件名称");
                    res.put("sn", "null");
                }
            }else {
                res.put("err_no", 2000);
                res.put("err_msg", "请输入filename参数");
                res.put("sn", "null");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(res.toString());
    }

你可能感兴趣的:(Web相关)