版权声明:本文为博主原创文章,未经博主同意不得转载。 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. Eureka客户端无法连接服务注册中心

    转载自:https://my.oschina.net/kousm/blog/2249003 服务端 application.yml配置 spring: application: name: eurek ...

  2. 使用 windows 批处理指令(BAT文件)进行文件删除、复制操作

    以下是做文件删除和复制的批处理指令 ::替换文件需要添加 /y 参数才能直接替换.不然会出现提示是否替换. ::复制Axis2Implementation和WebServices编译后的文件到tomc ...

  3. openldap 2.4 centos7 常用配置

    新版的openldap弃用了sldap.conf配置文件,引入一种动态配置,所以尽量不要直接修改配文件 如果直接修改了配置文件可以用slaptest -u命令检查 1.安装openldap,可能需要e ...

  4. 【html、CSS、javascript-12】jquery-效果

    一.jQuery 效果- 隐藏和显示 通过 jQuery,您可以使用 hide() 和 show() 方法来隐藏和显示 HTML 元素: $("#hide").click(func ...

  5. TZ_05_Spring_Proxy基于接口的动态代理和基于类的动态代理

    代理:为了增强方法在不添加代码的情况下 1.Proxy基于接口的动态代理 /** * 模拟一个消费者 * @author Administrator * */ public class Client ...

  6. union 和order by 使用时排序不正确

    静态专题和APP版专题(order by不起作用): [query] sql=(select sp_f13577,sp_f13576 from sp_t113 where url_1 not like ...

  7. HTTP协议②缓存

    首先介绍一下HTTP的报文信息,主要分成两个部分 1.包含属性的首部(header)---------------附加信息(cookie,缓存信息等)与缓存相关的规则信息,均包含在header中 2. ...

  8. 没有ORM库的时候,通过PDO连接MySQL的方法

    $pdo = new PDO("mysql:host=localhost;dbname=eq","root","root"); $pdo-& ...

  9. POJ1151 离散化求矩形面积的并

    /*第一道离散化的题目,虽然是水题,不过还是很高兴...*/ #include<cstdio> #include<algorithm> #include<cstring& ...

  10. linux-jdk-mysql-tomcat安装

    1.JDK安装 注意:rpm与软件相关命令 相当于window下的软件助手 管理软件 步骤: 1)查看当前Linux系统是否已经安装java 输入 rpm -qa | grep java 1)卸载两个 ...