语音听写 de 简单实现
一、前言
如果你没有在讯飞语音平台上创建应用,请先参考讯飞语音的详细配置使用
二、功能描述
语音听写和语音合成都是较为基础也是最常使用的两个基本功能。
语音合成是将文本转化为语音说出来,就是读文章。
语音听写是什么呢?
开启或者说触发语音听写的功能,我们开始讲话,然后讲话结束;该服务能将说话的内容转化为文本;
当然功能是这样,用途不仅仅是讲说话内容转化为文本。理解说话者的意图,这才是人工智能的方向。
这里我们简单的以一个小项目实例实现简单的语音听写。
三、项目实例
<1.1>项目结构如下图所示:
<2.1>.新建Android Application Project 项目,命名为TestHearerDemo,
<2.1.1>说明:
项目结构基本和上一个项目一样,如果看过上一个语音合成可直接跳过该步骤,去看代码实现部分。首先有几个注意点,避免初始化错误,讯飞语音版本自升级后要求,SDK 与 Appid 一一对应。导入配置文件到新建工程TestHearerDemo
<2.1.2>配置文件:
assets与libs 下的包
注意arm中的so文件必须与当前key值是对应的。就是创建应用时下载的 SDK中所包含的文件,appid 是创建应用时所产生的,不同的应用key值不同。
四、项目代码
<1.1>.test.layout布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="20dp"android:text="所说内容:" /><EditTextandroid: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" /><Buttonandroid:id="@+id/listen_btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="开始说话" /></LinearLayout>
<1.2>MainActivity.java 代码如下:
package pers.rfeng.demo;import java.util.HashMap;
import java.util.LinkedHashMap;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;public class MainActivity extends Activity implements OnClickListener {//存放听写分析结果文本private HashMap<String, String> hashMapTexts = new LinkedHashMap<String, String>();private Button b_btn; //初始化控件private EditText e_text;SpeechRecognizer hearer; //听写对象RecognizerDialog dialog; //讯飞提示框@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.test);b_btn = (Button) findViewById(R.id.listen_btn);e_text = (EditText) findViewById(R.id.content_et);b_btn.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.listen_btn:// 语音配置对象初始化SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID + "=57b2decc");// 1.创建SpeechRecognizer对象,第2个参数:本地听写时传InitListenerhearer = SpeechRecognizer.createRecognizer( MainActivity.this, null);// 交互动画dialog = new RecognizerDialog(MainActivity.this, null);// 2.设置听写参数,详见《科大讯飞MSC API手册(Android)》SpeechConstant类hearer.setParameter(SpeechConstant.DOMAIN, "iat"); // domain:域名hearer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");hearer.setParameter(SpeechConstant.ACCENT, "mandarin"); // mandarin:普通话//3.开始听写dialog.setListener(new RecognizerDialogListener() { //设置对话框@Overridepublic void onResult(RecognizerResult results, boolean isLast) {// TODO 自动生成的方法存根Log.d("Result", results.getResultString());//(1) 解析 json 数据<< 一个一个分析文本 >>StringBuffer strBuffer = new StringBuffer();try {JSONTokener tokener = new JSONTokener(results.getResultString());Log.i("TAG", "Test"+results.getResultString());Log.i("TAG", "Test"+results.toString());JSONObject joResult = new JSONObject(tokener);JSONArray words = joResult.getJSONArray("ws");for (int i = 0; i < words.length(); i++) {// 转写结果词,默认使用第一个结果JSONArray items = words.getJSONObject(i).getJSONArray("cw");JSONObject obj = items.getJSONObject(0);strBuffer.append(obj.getString("w"));}} catch (Exception e) {e.printStackTrace();}
// String text = strBuffer.toString();// (2)读取json结果中的sn字段String sn = null;try {JSONObject resultJson = new JSONObject(results.getResultString());sn = resultJson.optString("sn");} catch (JSONException e) {e.printStackTrace();}//(3) 解析语音文本<< 将文本叠加成语音分析结果 >>hashMapTexts.put(sn, strBuffer.toString());StringBuffer resultBuffer = new StringBuffer(); //最后结果for (String key : hashMapTexts.keySet()) {resultBuffer.append(hashMapTexts.get(key));}e_text.setText(resultBuffer.toString());e_text.requestFocus();//获取焦点e_text.setSelection(1);//将光标定位到文字最后,以便修改}@Overridepublic void onError(SpeechError error) {// TODO 自动生成的方法存根error.getPlainDescription(true);}});dialog.show(); //显示对话框break;default:break;}}
}
<1.3> AndroidManifest.xml 配置文件
注意权限配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="pers.rfeng.demo"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="17"android:targetSdkVersion="19" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="pers.rfeng.demo.MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><!-- 移动统计分析 --><meta-dataandroid:name="IFLYTEK_APPKEY"android:value="'57b2decc'" /><meta-dataandroid:name="IFLYTEK_CHANNEL"android:value="Android_Demo" /></application><!-- 连接网络权限,用于执行云端语音能力 --><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"/>
</manifest>
五、项目演示
运行项目效果如下:
界面可能有点儿不好看,嘻嘻
说明:
点击按钮,可以开始说话,讯飞语音默认说话最长时长不超过 1 分钟
语音听写分析结果显示
希望对你有所帮助,更多功能请参考开发文档