版权声明:本文为博主原创文章,未经博主同意不得转载。 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('\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;
}
}

百度语音识别REST API用法(含JAVA代码)——不须要集成SDK的方法的更多相关文章

  1. 百度语音识别REST API——通过使用Http网络请求方式获得语音识别功能

    百度语音识别通过REST API的方式给开发人员提供一个通用的HTTP接口,基于该接口,开发人员能够轻松的获取语音识别能力,本文档描写叙述了使用语音识别服务REST API的方法. 长处: 较之开发人 ...

  2. 十大经典排序算法最强总结(含JAVA代码实现)(转)

    十大经典排序算法最强总结(含JAVA代码实现)   最近几天在研究排序算法,看了很多博客,发现网上有的文章中对排序算法解释的并不是很透彻,而且有很多代码都是错误的,例如有的文章中在“桶排序”算法中对每 ...

  3. 爬虫技术之——bloom filter(含java代码)

    在爬虫系统中,在内存中维护着两个关于URL的队列,ToDo队列和Visited队列,ToDo队列存放的是爬虫从已经爬取的网页中解析出来的即将爬取的URL,但是网页是互联的,很可能解析出来的URL是已经 ...

  4. kafka中常用API的简单JAVA代码

    通过之前<kafka分布式消息队列介绍以及集群安装>的介绍,对kafka有了初步的了解.本文主要讲述java代码中常用的操作. 准备:增加kafka依赖 <dependency> ...

  5. Centos7.4简单安装使用gitlab+maven+jenkins实现java代码的持续集成部署

    1.工具的简单介绍 gitlab--源代码版本管理控制工具 maven--java代码编译构建工具 jenkins--基于java开发的自动化持续集成部署工具 sonar--代码质量管理工具 2.gi ...

  6. 使用百度语音识别REST API,做全平台语音识别

    百度语音开发介绍文档: http://yuyin.baidu.com/docs/asr# 使用语音识别,需要在百度申请一个应用,然后拿到API Key和Secret Key,然后才可以使用语音识别 p ...

  7. 十大经典排序算法最强总结(含JAVA代码实现)

    最近几天在研究排序算法,看了很多博客,发现网上有的文章中对排序算法解释的并不是很透彻,而且有很多代码都是错误的,例如有的文章中在“桶排序”算法中对每个桶进行排序直接使用了Collection.sort ...

  8. frida的用法--Hook Java代码篇

    frida是一款方便并且易用的跨平台Hook工具,使用它不仅可以Hook Java写的应用程序,而且还可以Hook原生的应用程序. 1. 准备 frida分客户端环境和服务端环境.在客户端我们可以编写 ...

  9. JAVA十大经典排序算法最强总结(含JAVA代码实现)

    十大经典排序算法最强总结(含JAVA代码实现)   最近几天在研究排序算法,看了很多博客,发现网上有的文章中对排序算法解释的并不是很透彻,而且有很多代码都是错误的,例如有的文章中在“桶排序”算法中对每 ...

随机推荐

  1. JasperReports报表变量13

    报表变量是建立在报表表达式之上的特殊对象.报表变量简化以下任务: 报表,其中大量使用在整个报告模板表达式.这些表达式可以通过使用报表变量只能声明一次. 计数,求和,平均,最低,最高,方差等:报表变量可 ...

  2. linux下C++遍历文件夹下的全部文件;Windows/Linux下C++批量修改文件名,批量删除文件

    Linux下 C++遍历目录下所有文件 rename(image_path.c_str(), image_path_new.c_str()); remove(image_path_move.c_str ...

  3. div 无缝滚动

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org ...

  4. Django项目:CRM(客户关系管理系统)--22--14PerfectCRM实现King_admin分页的省略显示

    {#table_data_list.html#} {## ————————08PerfectCRM实现King_admin显示注册表的字段表头————————#} {% extends 'king_m ...

  5. animation-fill-mode 之 forwards , transition-timing-function的取值 和 transform属性

    animation-fill-mode 有四个值可选,并且允许由逗号分隔多个值. none 不改变默认行为. forwards 当动画完成后,保持最后一个属性值(在最后一个关键帧中定义). backw ...

  6. [转]深入理解定位父级offsetParent及偏移大小

    偏移量(offset dimension)是javascript中的一个重要的概念.涉及到偏移量的主要是offsetLeft.offsetTop.offsetHeight.offsetWidth这四个 ...

  7. cookie-在关闭浏览器之前弹框只弹一次

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  8. ztree树节点重叠问题

    使用zTree时,由于同时使用了bootstrap插件,导致样式起了冲突,生成的树都挤在一起了, 最后的解决办法是设置zTreeStyle.css文件的.ztree li ul{}属性,在里面加入he ...

  9. Linux环境变量的种类

    按环境变量的生存周期来划分,Linux的环境变量可分为两类: 1永久的:需要修改配置文件,变量永久生效. 2临时的:使用export命令行声明即可,变量在关闭shell时失效.

  10. 集训队日常训练20180513-DIV1

    A.3132 给一个有向图,问能否从任意点出发都能进入一个环中. 深搜. #include<bits/stdc++.h> using namespace std; ; vector< ...