准备工作
1.首先要在科大讯飞开放平台(http://www.xfyun.cn/)上注册;
2.右上角进入控制台,按照说明创建一个应用,该应用名就叫HITOSLabTest(与android studio的项目名一致),创建成功后会有一个AppID,记下来,编程的时候要用到;
3.点击HITOSLabTest后面的“开通服务”按钮,开通服务—>语音听写,进入语音听写—>下载当前应用对应的SDK;
4.下载Android版的SDK,将SDK包中libs目录所有文件复制到Android工程的libs目录中,把SDK包中assets目录下的iflytek文件夹复制到工程的assets目录下,如下图所示。
5.一般libs下还缺少一个gson的jar文件,需要自行下载;
代码实现
1.activity_main.xml,app界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/listen_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始说话" />
<TextView
android:id="@+id/task_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="日程安排:" />
<EditText
android:id="@+id/content_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_dropdown_light_frame"
android:cursorVisible="true"
android:enabled="true"
android:gravity="top"
android:visibility="visible" />
</LinearLayout>
2.MainActivity
package com.example.administrator.hitoslabtest;
import java.lang.reflect.Type;
import java.util.List;
//import com.example.speechrecognition.DictationResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static String APPID = "584a6981";
private Button listenBtn;
private EditText contentEt;
// 听写结果字符串(多个Json的列表字符串)
private String dictationResultStr = "[";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listenBtn = (Button) findViewById(R.id.listen_btn);
contentEt = (EditText) findViewById(R.id.content_et);
listenBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.listen_btn:
dictationResultStr = "[";
// 语音配置对象初始化
SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID
+ "=" + APPID);
// 1.创建SpeechRecognizer对象,第2个参数:本地听写时传InitListener
SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(
MainActivity.this, null);
// 交互动画
RecognizerDialog iatDialog = new RecognizerDialog(
MainActivity.this, null);
// 2.设置听写参数,详见《科大讯飞MSC API手册(Android)》SpeechConstant类
mIat.setParameter(SpeechConstant.DOMAIN, "iat"); // domain:域名
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
mIat.setParameter(SpeechConstant.ACCENT, "mandarin"); // mandarin:普通话
//3.开始听写
iatDialog.setListener(new RecognizerDialogListener() {
@Override
public void onResult(RecognizerResult results, boolean isLast) {
// TODO 自动生成的方法存根
// Log.d("Result", results.getResultString());
// contentTv.setText(results.getResultString());
if (!isLast) {
dictationResultStr += results.getResultString() + ",";
} else {
dictationResultStr += results.getResultString() + "]";
}
if (isLast) {
// 解析Json列表字符串
Gson gson = new Gson();
List<DictationResult> dictationResultList = gson
.fromJson(dictationResultStr,
new TypeToken<List<DictationResult>>() {
}.getType());
String finalResult = "";
for (int i = 0; i < dictationResultList.size() - 1; i++) {
finalResult += dictationResultList.get(i)
.toString();
}
contentEt.setText(finalResult);
//获取焦点
contentEt.requestFocus();
//将光标定位到文字最后,以便修改
contentEt.setSelection(finalResult.length());
Log.d("From reall phone", finalResult);
}
}
@Override
public void onError(SpeechError error) {
// TODO 自动生成的方法存根
error.getPlainDescription(true);
}
});
// 开始听写
iatDialog.show();
break;
default:
break;
}
}
}
3.com.example.administrator.hitoslabtest.DictationResult文件
package com.example.administrator.hitoslabtest;
import java.util.List;
/**
* 解析语音听写返回结果Json格式字符串的模板类(多重嵌套Json)
*
* 语音识别结果Json数据格式(单条数据):
* {"sn":1,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"w":"今天","sc":0}]},
* {"bg":0,"cw":{"w":"的","sc":0}]},{"bg":0,"cw":[{"w":"天气","sc":0}]},
* {"bg":0,"cw":[{"w":"怎么样","sc":0}]},{"bg":0,"cw":[{"w":"。","sc":0}]}]}
*/
public class DictationResult {
private String sn;
private String ls;
private String bg;
private String ed;
private List<Words> ws;
public static class Words {
private String bg;
private List<Cw> cw;
public static class Cw {
private String w;
private String sc;
public String getW() {
return w;
}
public void setW(String w) {
this.w = w;
}
public String getSc() {
return sc;
}
public void setSc(String sc) {
this.sc = sc;
}
@Override
public String toString() {
return w;
}
}
public String getBg() {
return bg;
}
public void setBg(String bg) {
this.bg = bg;
}
public List<Cw> getCw() {
return cw;
}
public void setCw(List<Cw> cw) {
this.cw = cw;
}
@Override
public String toString() {
String result = "";
for (Cw cwTmp : cw) {
result += cwTmp.toString();
}
return result;
}
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getLs() {
return ls;
}
public void setLs(String ls) {
this.ls = ls;
}
public String getBg() {
return bg;
}
public void setBg(String bg) {
this.bg = bg;
}
public String getEd() {
return ed;
}
public void setEd(String ed) {
this.ed = ed;
}
public List<Words> getWs() {
return ws;
}
public void setWs(List<Words> ws) {
this.ws = ws;
}
@Override
public String toString() {
String result = "";
for (Words wsTmp : ws) {
result += wsTmp.toString();
}
return result;
}
4.AndroidManifest.xml中申请权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.hitoslabtest">
<!-- 连接网络权限,用于执行云端语音能力 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 获取手机录音机使用权限,听写、识别、语义理解需要用到此权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!--读取网络信息状态 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--获取当前wifi状态 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!--允许程序改变网络连接状态 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<!--读取手机信息权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!--读取联系人权限,上传联系人需要用到此权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
5.添加jnilibs
修改Gradle Scripts 中的build.gradle(Module:app)文件,如上图
具体修改:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.administrator.hitoslabtest"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'
}