滨化讯飞插件

This commit is contained in:
万昕放 2022-11-19 10:53:39 +08:00
parent f46962da29
commit 5e5aed2682
70 changed files with 4339 additions and 4506 deletions

Binary file not shown.

Binary file not shown.

View File

@ -1,14 +1,13 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
android { android {
compileSdkVersion 28 compileSdkVersion 30
buildToolsVersion '26.0.2' buildToolsVersion "30.0.3"
defaultConfig { defaultConfig {
applicationId "com.iflytek.voicedemo" applicationId "com.iflytek.voicedemo"
minSdkVersion 9 minSdkVersion 16
targetSdkVersion 28 targetSdkVersion 30
} }
buildTypes { buildTypes {
@ -26,17 +25,15 @@ android {
allprojects { allprojects {
repositories { repositories {
google()
jcenter()
mavenCentral() mavenCentral()
} }
} }
} }
dependencies { dependencies {
compile files('libs/Msc.jar') implementation files('libs/Msc.jar')
// compile project(':MscLibSrc') implementation 'androidx.legacy:legacy-support-v4:1.0.0'
compile 'com.android.support:support-v4:23.+' implementation 'com.google.android.material:material:1.4.0'
} }

View File

@ -1,3 +1,2 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<lint> <lint></lint>
</lint>

View File

@ -2,88 +2,81 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iflytek.voicedemo" package="com.iflytek.voicedemo"
android:versionCode="1" android:versionCode="1"
android:versionName="2.0.1018.1013" > android:versionName="2.0.1018.1013">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application <application
android:icon="@drawable/icon" android:icon="@drawable/icon"
android:name="SpeechApp" android:name="SpeechApp"
android:label="讯飞语音示例" > android:label="讯飞语音示例">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.iflytek.voicedemo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity <activity
android:name="com.iflytek.voicedemo.MainActivity" android:name="com.iflytek.voicedemo.MainActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:icon="@drawable/icon" android:icon="@drawable/icon"
android:label="讯飞语音示例" android:label="讯飞语音示例"
android:screenOrientation="portrait" > android:screenOrientation="portrait">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name="com.iflytek.speech.setting.TtsSettings" > <activity android:name="com.iflytek.speech.setting.TtsSettings" />
</activity> <activity android:name="com.iflytek.speech.setting.IatSettings" />
<activity android:name="com.iflytek.speech.setting.IatSettings" >
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.IatDemo" android:name="com.iflytek.voicedemo.IatDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.AsrDemo" android:name="com.iflytek.voicedemo.AsrDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.TtsDemo" android:name="com.iflytek.voicedemo.TtsDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.IseDemo" android:name="com.iflytek.voicedemo.IseDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity
android:name="com.iflytek.voicedemo.vocalverify.VocalVerifyDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.faceonline.OnlineFaceDemo" android:name="com.iflytek.voicedemo.faceonline.OnlineFaceDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.IdentifyGroup.GroupManagerActivity" android:name="com.iflytek.voicedemo.IdentifyGroup.GroupManagerActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait"> android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.IdentifyGroup.FaceIdentifyActivity" android:name="com.iflytek.voicedemo.IdentifyGroup.FaceIdentifyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait"> android:screenOrientation="portrait" />
</activity>
<activity
android:name="com.iflytek.voicedemo.IdentifyGroup.VocalIdentifyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait">
</activity>
<activity <activity
android:name="com.iflytek.voicedemo.IdentifyGroup.ResultIdentifyActivity" android:name="com.iflytek.voicedemo.IdentifyGroup.ResultIdentifyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait"> android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.speech.setting.IseSettings" android:name="com.iflytek.speech.setting.IseSettings"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<activity <activity
android:name="com.iflytek.speech.setting.UrlSettings" android:name="com.iflytek.speech.setting.UrlSettings"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" > android:screenOrientation="portrait" />
</activity>
<!-- 移动统计分析 --> <!-- 移动统计分析 -->
<meta-data <meta-data
android:name="IFLYTEK_APPKEY" android:name="IFLYTEK_APPKEY"
@ -95,20 +88,4 @@
</application> </application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest> </manifest>

View File

@ -12,12 +12,12 @@ package com.iflytek.ise.result;
*/ */
public class FinalResult extends Result { public class FinalResult extends Result {
public int ret; public int ret;
public float total_score; public float total_score;
@Override @Override
public String toString() { public String toString() {
return "返回值:" + ret + ",总分:" + total_score; return "返回值:" + ret + ",总分:" + total_score;
} }
} }

View File

@ -14,32 +14,32 @@ import com.iflytek.ise.result.util.ResultFormatUtil;
*/ */
public class ReadSentenceResult extends Result { public class ReadSentenceResult extends Result {
public ReadSentenceResult() { public ReadSentenceResult() {
category = "read_sentence"; category = "read_sentence";
} }
@Override @Override
public String toString() { public String toString() {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
if ("cn".equals(language)) { if ("cn".equals(language)) {
buffer.append("[总体结果]\n") buffer.append("[总体结果]\n")
.append("评测内容:" + content + "\n") .append("评测内容:" + content + "\n")
.append("朗读时长:" + time_len + "\n") .append("朗读时长:" + time_len + "\n")
.append("总分:" + total_score + "\n\n") .append("总分:" + total_score + "\n\n")
.append("[朗读详情]").append(ResultFormatUtil.formatDetails_CN(sentences)); .append("[朗读详情]").append(ResultFormatUtil.formatDetails_CN(sentences));
} else { } else {
if (is_rejected) { if (is_rejected) {
buffer.append("检测到乱读,") buffer.append("检测到乱读,")
.append("except_info:" + except_info + "\n\n"); // except_info代码说明详见语音评测参数结果说明文档 .append("except_info:" + except_info + "\n\n"); // except_info代码说明详见语音评测参数结果说明文档
} }
buffer.append("[总体结果]\n") buffer.append("[总体结果]\n")
.append("评测内容:" + content + "\n") .append("评测内容:" + content + "\n")
.append("总分:" + total_score + "\n\n") .append("总分:" + total_score + "\n\n")
.append("[朗读详情]").append(ResultFormatUtil.formatDetails_EN(sentences)); .append("[朗读详情]").append(ResultFormatUtil.formatDetails_EN(sentences));
} }
return buffer.toString(); return buffer.toString();
} }
} }

View File

@ -14,20 +14,20 @@ import com.iflytek.ise.result.util.ResultFormatUtil;
*/ */
public class ReadSyllableResult extends Result { public class ReadSyllableResult extends Result {
public ReadSyllableResult() { public ReadSyllableResult() {
language = "cn"; language = "cn";
category = "read_syllable"; category = "read_syllable";
} }
@Override @Override
public String toString() { public String toString() {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
buffer.append("[总体结果]\n") buffer.append("[总体结果]\n")
.append("评测内容:" + content + "\n") .append("评测内容:" + content + "\n")
.append("朗读时长:" + time_len + "\n") .append("朗读时长:" + time_len + "\n")
.append("总分:" + total_score + "\n\n") .append("总分:" + total_score + "\n\n")
.append("[朗读详情]").append(ResultFormatUtil.formatDetails_CN(sentences)); .append("[朗读详情]").append(ResultFormatUtil.formatDetails_CN(sentences));
return buffer.toString(); return buffer.toString();
} }
} }

View File

@ -14,34 +14,34 @@ import com.iflytek.ise.result.util.ResultFormatUtil;
*/ */
public class ReadWordResult extends Result { public class ReadWordResult extends Result {
public ReadWordResult() { public ReadWordResult() {
category = "read_word"; category = "read_word";
} }
@Override @Override
public String toString() { public String toString() {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
if ("cn".equals(language)) { if ("cn".equals(language)) {
buffer.append("[总体结果]\n") buffer.append("[总体结果]\n")
.append("评测内容:" + content + "\n") .append("评测内容:" + content + "\n")
.append("朗读时长:" + time_len + "\n") .append("朗读时长:" + time_len + "\n")
.append("总分:" + total_score + "\n\n") .append("总分:" + total_score + "\n\n")
.append("[朗读详情]") .append("[朗读详情]")
.append(ResultFormatUtil.formatDetails_CN(sentences)); .append(ResultFormatUtil.formatDetails_CN(sentences));
} else { } else {
if (is_rejected) { if (is_rejected) {
buffer.append("检测到乱读,") buffer.append("检测到乱读,")
.append("except_info:" + except_info + "\n\n"); // except_info代码说明详见语音评测参数结果说明文档 .append("except_info:" + except_info + "\n\n"); // except_info代码说明详见语音评测参数结果说明文档
} }
buffer.append("[总体结果]\n") buffer.append("[总体结果]\n")
.append("评测内容:" + content + "\n") .append("评测内容:" + content + "\n")
.append("总分:" + total_score + "\n\n") .append("总分:" + total_score + "\n\n")
.append("[朗读详情]") .append("[朗读详情]")
.append(ResultFormatUtil.formatDetails_EN(sentences)); .append(ResultFormatUtil.formatDetails_EN(sentences));
} }
return buffer.toString(); return buffer.toString();
} }
} }

View File

@ -3,10 +3,10 @@
*/ */
package com.iflytek.ise.result; package com.iflytek.ise.result;
import java.util.ArrayList;
import com.iflytek.ise.result.entity.Sentence; import com.iflytek.ise.result.entity.Sentence;
import java.util.ArrayList;
/** /**
* <p>Title: Result</p> * <p>Title: Result</p>
* <p>Description: 评测结果</p> * <p>Description: 评测结果</p>
@ -15,44 +15,44 @@ import com.iflytek.ise.result.entity.Sentence;
* @date 2015年1月12日 下午4:58:38 * @date 2015年1月12日 下午4:58:38
*/ */
public class Result { public class Result {
/** /**
* 评测语种en英文cn中文 * 评测语种en英文cn中文
*/ */
public String language; public String language;
/** /**
* 评测种类read_syllablecn单字read_word词语read_sentence句子 * 评测种类read_syllablecn单字read_word词语read_sentence句子
*/ */
public String category; public String category;
/** /**
* 开始帧位置每帧相当于10ms * 开始帧位置每帧相当于10ms
*/ */
public int beg_pos; public int beg_pos;
/** /**
* 结束帧位置 * 结束帧位置
*/ */
public int end_pos; public int end_pos;
/** /**
* 评测内容 * 评测内容
*/ */
public String content; public String content;
/** /**
* 总得分 * 总得分
*/ */
public float total_score; public float total_score;
/** /**
* 时长cn * 时长cn
*/ */
public int time_len; public int time_len;
/** /**
* 异常信息en * 异常信息en
*/ */
public String except_info; public String except_info;
/** /**
* 是否乱读cn * 是否乱读cn
*/ */
public boolean is_rejected; public boolean is_rejected;
/** /**
* xml结果中的sentence标签 * xml结果中的sentence标签
*/ */
public ArrayList<Sentence> sentences; public ArrayList<Sentence> sentences;
} }

View File

@ -13,93 +13,93 @@ import java.util.HashMap;
* @date 2015年1月12日 下午3:55:56 * @date 2015年1月12日 下午3:55:56
*/ */
public class Phone { public class Phone {
/** /**
* 讯飞音标-标准音标映射表en * 讯飞音标-标准音标映射表en
*/ */
public static HashMap<String, String> phone_map = new HashMap<String, String>(); public static HashMap<String, String> phone_map = new HashMap<String, String>();
static { static {
phone_map.put("aa", "ɑ:"); phone_map.put("aa", "ɑ:");
phone_map.put("oo", "ɔ"); phone_map.put("oo", "ɔ");
phone_map.put("ae", "æ"); phone_map.put("ae", "æ");
phone_map.put("ah", "ʌ"); phone_map.put("ah", "ʌ");
phone_map.put("ao", "ɔ:"); phone_map.put("ao", "ɔ:");
phone_map.put("aw", ""); phone_map.put("aw", "");
phone_map.put("ax", "ə"); phone_map.put("ax", "ə");
phone_map.put("ay", "aɪ"); phone_map.put("ay", "aɪ");
phone_map.put("eh", "e"); phone_map.put("eh", "e");
phone_map.put("er", "ə:"); phone_map.put("er", "ə:");
phone_map.put("ey", "eɪ"); phone_map.put("ey", "eɪ");
phone_map.put("ih", "ɪ"); phone_map.put("ih", "ɪ");
phone_map.put("iy", "i:"); phone_map.put("iy", "i:");
phone_map.put("ow", "əʊ"); phone_map.put("ow", "əʊ");
phone_map.put("oy", "ɔɪ"); phone_map.put("oy", "ɔɪ");
phone_map.put("uh", "ʊ"); phone_map.put("uh", "ʊ");
phone_map.put("uw", "ʊ:"); phone_map.put("uw", "ʊ:");
phone_map.put("ch", ""); phone_map.put("ch", "");
phone_map.put("dh", "ð"); phone_map.put("dh", "ð");
phone_map.put("hh", "h"); phone_map.put("hh", "h");
phone_map.put("jh", ""); phone_map.put("jh", "");
phone_map.put("ng", "ŋ"); phone_map.put("ng", "ŋ");
phone_map.put("sh", "ʃ"); phone_map.put("sh", "ʃ");
phone_map.put("th", "θ"); phone_map.put("th", "θ");
phone_map.put("zh", "ʒ"); phone_map.put("zh", "ʒ");
phone_map.put("y", "j"); phone_map.put("y", "j");
phone_map.put("d", "d"); phone_map.put("d", "d");
phone_map.put("k", "k"); phone_map.put("k", "k");
phone_map.put("l", "l"); phone_map.put("l", "l");
phone_map.put("m", "m"); phone_map.put("m", "m");
phone_map.put("n", "n"); phone_map.put("n", "n");
phone_map.put("b", "b"); phone_map.put("b", "b");
phone_map.put("f", "f"); phone_map.put("f", "f");
phone_map.put("g", "g"); phone_map.put("g", "g");
phone_map.put("p", "p"); phone_map.put("p", "p");
phone_map.put("r", "r"); phone_map.put("r", "r");
phone_map.put("s", "s"); phone_map.put("s", "s");
phone_map.put("t", "t"); phone_map.put("t", "t");
phone_map.put("v", "v"); phone_map.put("v", "v");
phone_map.put("w", "w"); phone_map.put("w", "w");
phone_map.put("z", "z"); phone_map.put("z", "z");
phone_map.put("ar", ""); phone_map.put("ar", "");
phone_map.put("ir", ""); phone_map.put("ir", "");
phone_map.put("ur", "ʊə"); phone_map.put("ur", "ʊə");
phone_map.put("tr", "tr"); phone_map.put("tr", "tr");
phone_map.put("dr", "dr"); phone_map.put("dr", "dr");
phone_map.put("ts", "ts"); phone_map.put("ts", "ts");
phone_map.put("dz", "dz"); phone_map.put("dz", "dz");
} }
/** /**
* 开始帧位置每帧相当于10ms * 开始帧位置每帧相当于10ms
*/ */
public int beg_pos; public int beg_pos;
/** /**
* 结束帧位置 * 结束帧位置
*/ */
public int end_pos; public int end_pos;
/** /**
* 音素内容 * 音素内容
*/ */
public String content; public String content;
/** /**
* 增漏读信息0正确16漏读32增读64回读128替换 * 增漏读信息0正确16漏读32增读64回读128替换
*/ */
public int dp_message; public int dp_message;
/** /**
* 时长单位每帧相当于10mscn * 时长单位每帧相当于10mscn
*/ */
public int time_len; public int time_len;
/** /**
* 得到content对应的标准音标en * 得到content对应的标准音标en
*/ */
public String getStdSymbol() { public String getStdSymbol() {
return getStdSymbol(content); return getStdSymbol(content);
} }
public static String getStdSymbol(String content) { public static String getStdSymbol(String content) {
String std = phone_map.get(content); String std = phone_map.get(content);
return (null == std)? content: std; return (null == std) ? content : std;
} }
} }

View File

@ -13,36 +13,36 @@ import java.util.ArrayList;
* @date 2015年1月12日 下午4:10:09 * @date 2015年1月12日 下午4:10:09
*/ */
public class Sentence { public class Sentence {
/** /**
* 开始帧位置每帧相当于10ms * 开始帧位置每帧相当于10ms
*/ */
public int beg_pos; public int beg_pos;
/** /**
* 结束帧位置 * 结束帧位置
*/ */
public int end_pos; public int end_pos;
/** /**
* 句子内容 * 句子内容
*/ */
public String content; public String content;
/** /**
* 总得分 * 总得分
*/ */
public float total_score; public float total_score;
/** /**
* 时长单位每帧相当于10mscn * 时长单位每帧相当于10mscn
*/ */
public int time_len; public int time_len;
/** /**
* 句子的索引en * 句子的索引en
*/ */
public int index; public int index;
/** /**
* 单词数en * 单词数en
*/ */
public int word_count; public int word_count;
/** /**
* sentence包括的word * sentence包括的word
*/ */
public ArrayList<Word> words; public ArrayList<Word> words;
} }

View File

@ -13,48 +13,48 @@ import java.util.ArrayList;
* @date 2015年1月12日 下午3:49:51 * @date 2015年1月12日 下午3:49:51
*/ */
public class Syll { public class Syll {
/** /**
* 开始帧位置每帧相当于10ms * 开始帧位置每帧相当于10ms
*/ */
public int beg_pos; public int beg_pos;
/** /**
* 结束帧位置 * 结束帧位置
*/ */
public int end_pos; public int end_pos;
/** /**
* 音节内容 * 音节内容
*/ */
public String content; public String content;
/** /**
* 拼音cn数字代表声调5表示轻声如fen1 * 拼音cn数字代表声调5表示轻声如fen1
*/ */
public String symbol; public String symbol;
/** /**
* 增漏读信息0正确16漏读32增读64回读128替换 * 增漏读信息0正确16漏读32增读64回读128替换
*/ */
public int dp_message; public int dp_message;
/** /**
* 时长单位每帧相当于10mscn * 时长单位每帧相当于10mscn
*/ */
public int time_len; public int time_len;
/** /**
* Syll包含的音节 * Syll包含的音节
*/ */
public ArrayList<Phone> phones; public ArrayList<Phone> phones;
/** /**
* 获取音节的标准音标en * 获取音节的标准音标en
* *
* @return 标准音标 * @return 标准音标
*/ */
public String getStdSymbol() { public String getStdSymbol() {
String stdSymbol = ""; String stdSymbol = "";
String[] symbols = content.split(" "); String[] symbols = content.split(" ");
for (int i = 0; i < symbols.length; i++) { for (int i = 0; i < symbols.length; i++) {
stdSymbol += Phone.getStdSymbol(symbols[i]); stdSymbol += Phone.getStdSymbol(symbols[i]);
} }
return stdSymbol; return stdSymbol;
} }
} }

View File

@ -13,45 +13,45 @@ import java.util.ArrayList;
* @date 2015年1月12日 下午3:29:30 * @date 2015年1月12日 下午3:29:30
*/ */
public class Word { public class Word {
/** /**
* 开始帧位置每帧相当于10ms * 开始帧位置每帧相当于10ms
*/ */
public int beg_pos; public int beg_pos;
/** /**
* 结束帧位置 * 结束帧位置
*/ */
public int end_pos; public int end_pos;
/** /**
* 单词内容 * 单词内容
*/ */
public String content; public String content;
/** /**
* 增漏读信息0正确16漏读32增读64回读128替换 * 增漏读信息0正确16漏读32增读64回读128替换
*/ */
public int dp_message; public int dp_message;
/** /**
* 单词在全篇索引en * 单词在全篇索引en
*/ */
public int global_index; public int global_index;
/** /**
* 单词在句子中的索引en * 单词在句子中的索引en
*/ */
public int index; public int index;
/** /**
* 拼音cn数字代表声调5表示轻声如fen1 * 拼音cn数字代表声调5表示轻声如fen1
*/ */
public String symbol; public String symbol;
/** /**
* 时长单位每帧相当于10mscn * 时长单位每帧相当于10mscn
*/ */
public int time_len; public int time_len;
/** /**
* 单词得分en * 单词得分en
*/ */
public float total_score; public float total_score;
/** /**
* Word包含的Syll * Word包含的Syll
*/ */
public ArrayList<Syll> sylls; public ArrayList<Syll> sylls;
} }

View File

@ -3,13 +3,13 @@
*/ */
package com.iflytek.ise.result.util; package com.iflytek.ise.result.util;
import java.util.ArrayList;
import com.iflytek.ise.result.entity.Phone; import com.iflytek.ise.result.entity.Phone;
import com.iflytek.ise.result.entity.Sentence; import com.iflytek.ise.result.entity.Sentence;
import com.iflytek.ise.result.entity.Syll; import com.iflytek.ise.result.entity.Syll;
import com.iflytek.ise.result.entity.Word; import com.iflytek.ise.result.entity.Word;
import java.util.ArrayList;
/** /**
* <p>Title: ResultFormatUtl</p> * <p>Title: ResultFormatUtl</p>
* <p>Description: </p> * <p>Description: </p>
@ -19,104 +19,104 @@ import com.iflytek.ise.result.entity.Word;
*/ */
public class ResultFormatUtil { public class ResultFormatUtil {
/** /**
* 将英语评测详情按格式输出 * 将英语评测详情按格式输出
* *
* @param sentences * @param sentences
* @return 英语评测详情 * @return 英语评测详情
*/ */
public static String formatDetails_EN(ArrayList<Sentence> sentences) { public static String formatDetails_EN(ArrayList<Sentence> sentences) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
if (null == sentences) { if (null == sentences) {
return buffer.toString(); return buffer.toString();
} }
for (Sentence sentence: sentences ) { for (Sentence sentence : sentences) {
if ("噪音".equals(ResultTranslateUtil.getContent(sentence.content)) if ("噪音".equals(ResultTranslateUtil.getContent(sentence.content))
|| "静音".equals(ResultTranslateUtil.getContent(sentence.content))) { || "静音".equals(ResultTranslateUtil.getContent(sentence.content))) {
continue; continue;
} }
if (null == sentence.words) { if (null == sentence.words) {
continue; continue;
} }
for (Word word: sentence.words) { for (Word word : sentence.words) {
if ("噪音".equals(ResultTranslateUtil.getContent(word.content)) if ("噪音".equals(ResultTranslateUtil.getContent(word.content))
|| "静音".equals(ResultTranslateUtil.getContent(word.content))) { || "静音".equals(ResultTranslateUtil.getContent(word.content))) {
continue; continue;
} }
buffer.append("\n单词[" + ResultTranslateUtil.getContent(word.content) + "] ") buffer.append("\n单词[" + ResultTranslateUtil.getContent(word.content) + "] ")
.append("朗读:" + ResultTranslateUtil.getDpMessageInfo(word.dp_message)) .append("朗读:" + ResultTranslateUtil.getDpMessageInfo(word.dp_message))
.append(" 得分:" + word.total_score); .append(" 得分:" + word.total_score);
if (null == word.sylls) { if (null == word.sylls) {
buffer.append("\n"); buffer.append("\n");
continue; continue;
} }
for (Syll syll: word.sylls) { for (Syll syll : word.sylls) {
buffer.append("\n└音节[" + ResultTranslateUtil.getContent(syll.getStdSymbol()) + "] "); buffer.append("\n└音节[" + ResultTranslateUtil.getContent(syll.getStdSymbol()) + "] ");
if (null == syll.phones) { if (null == syll.phones) {
continue; continue;
} }
for (Phone phone: syll.phones) { for (Phone phone : syll.phones) {
buffer.append("\n\t└音素[" + ResultTranslateUtil.getContent(phone.getStdSymbol()) + "] ") buffer.append("\n\t└音素[" + ResultTranslateUtil.getContent(phone.getStdSymbol()) + "] ")
.append(" 朗读:" + ResultTranslateUtil.getDpMessageInfo(phone.dp_message)); .append(" 朗读:" + ResultTranslateUtil.getDpMessageInfo(phone.dp_message));
} }
} }
buffer.append("\n"); buffer.append("\n");
} }
} }
return buffer.toString(); return buffer.toString();
} }
/** /**
* 将汉语评测详情按格式输出 * 将汉语评测详情按格式输出
* *
* @param sentences * @param sentences
* @return 汉语评测详情 * @return 汉语评测详情
*/ */
public static String formatDetails_CN(ArrayList<Sentence> sentences) { public static String formatDetails_CN(ArrayList<Sentence> sentences) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
if (null == sentences) { if (null == sentences) {
return buffer.toString(); return buffer.toString();
} }
for (Sentence sentence: sentences ) { for (Sentence sentence : sentences) {
if (null == sentence.words) { if (null == sentence.words) {
continue; continue;
} }
for (Word word: sentence.words) { for (Word word : sentence.words) {
buffer.append("\n词语[" + ResultTranslateUtil.getContent(word.content) + "] " + word.symbol + " 时长:" + word.time_len); buffer.append("\n词语[" + ResultTranslateUtil.getContent(word.content) + "] " + word.symbol + " 时长:" + word.time_len);
if (null == word.sylls) { if (null == word.sylls) {
continue; continue;
} }
for (Syll syll: word.sylls) { for (Syll syll : word.sylls) {
if ("噪音".equals(ResultTranslateUtil.getContent(syll.content)) if ("噪音".equals(ResultTranslateUtil.getContent(syll.content))
|| "静音".equals(ResultTranslateUtil.getContent(syll.content))) { || "静音".equals(ResultTranslateUtil.getContent(syll.content))) {
continue; continue;
} }
buffer.append("\n└音节[" + ResultTranslateUtil.getContent(syll.content) + "] " + syll.symbol + " 时长:" + syll.time_len); buffer.append("\n└音节[" + ResultTranslateUtil.getContent(syll.content) + "] " + syll.symbol + " 时长:" + syll.time_len);
if (null == syll.phones) { if (null == syll.phones) {
continue; continue;
} }
for (Phone phone: syll.phones) { for (Phone phone : syll.phones) {
buffer.append("\n\t└音素[" + ResultTranslateUtil.getContent(phone.content) + "] " + "时长:" + phone.time_len) buffer.append("\n\t└音素[" + ResultTranslateUtil.getContent(phone.content) + "] " + "时长:" + phone.time_len)
.append(" 朗读:" + ResultTranslateUtil.getDpMessageInfo(phone.dp_message)); .append(" 朗读:" + ResultTranslateUtil.getDpMessageInfo(phone.dp_message));
} }
} }
buffer.append("\n"); buffer.append("\n");
} }
} }
return buffer.toString(); return buffer.toString();
} }
} }

View File

@ -14,27 +14,27 @@ import java.util.HashMap;
*/ */
public class ResultTranslateUtil { public class ResultTranslateUtil {
private static HashMap<Integer, String> dp_message_map = new HashMap<Integer, String>(); private static HashMap<Integer, String> dp_message_map = new HashMap<Integer, String>();
private static HashMap<String, String> special_content_map = new HashMap<String, String>(); private static HashMap<String, String> special_content_map = new HashMap<String, String>();
static { static {
dp_message_map.put(0, "正常"); dp_message_map.put(0, "正常");
dp_message_map.put(16, "漏读"); dp_message_map.put(16, "漏读");
dp_message_map.put(32, "增读"); dp_message_map.put(32, "增读");
dp_message_map.put(64, "回读"); dp_message_map.put(64, "回读");
dp_message_map.put(128, "替换"); dp_message_map.put(128, "替换");
special_content_map.put("sil", "静音"); special_content_map.put("sil", "静音");
special_content_map.put("silv", "静音"); special_content_map.put("silv", "静音");
special_content_map.put("fil", "噪音"); special_content_map.put("fil", "噪音");
} }
public static String getDpMessageInfo(int dp_message) { public static String getDpMessageInfo(int dp_message) {
return dp_message_map.get(dp_message); return dp_message_map.get(dp_message);
} }
public static String getContent(String content) { public static String getContent(String content) {
String val = special_content_map.get(content); String val = special_content_map.get(content);
return (null == val)? content: val; return (null == val) ? content : val;
} }
} }

View File

@ -3,14 +3,6 @@
*/ */
package com.iflytek.ise.result.xml; package com.iflytek.ise.result.xml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Xml; import android.util.Xml;
@ -24,6 +16,14 @@ import com.iflytek.ise.result.entity.Sentence;
import com.iflytek.ise.result.entity.Syll; import com.iflytek.ise.result.entity.Syll;
import com.iflytek.ise.result.entity.Word; import com.iflytek.ise.result.entity.Word;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/** /**
* <p>Title: XmlResultParser</p> * <p>Title: XmlResultParser</p>
* <p>Description: </p> * <p>Description: </p>
@ -33,247 +33,247 @@ import com.iflytek.ise.result.entity.Word;
*/ */
public class XmlResultParser { public class XmlResultParser {
public Result parse(String xml) { public Result parse(String xml) {
if (TextUtils.isEmpty(xml)) { if (TextUtils.isEmpty(xml)) {
return null; return null;
} }
XmlPullParser pullParser = Xml.newPullParser(); XmlPullParser pullParser = Xml.newPullParser();
try { try {
InputStream ins = new ByteArrayInputStream(xml.getBytes()); InputStream ins = new ByteArrayInputStream(xml.getBytes());
pullParser.setInput(ins, "utf-8"); pullParser.setInput(ins, "utf-8");
FinalResult finalResult = null; FinalResult finalResult = null;
int eventType = pullParser.getEventType(); int eventType = pullParser.getEventType();
while (XmlPullParser.END_DOCUMENT != eventType) { while (XmlPullParser.END_DOCUMENT != eventType) {
switch (eventType) { switch (eventType) {
case XmlPullParser.START_TAG: case XmlPullParser.START_TAG:
if ("FinalResult".equals(pullParser.getName())) { if ("FinalResult".equals(pullParser.getName())) {
// 只有一个总分的结果 // 只有一个总分的结果
finalResult = new FinalResult(); finalResult = new FinalResult();
} else if ("ret".equals(pullParser.getName())) { } else if ("ret".equals(pullParser.getName())) {
finalResult.ret = getInt(pullParser, "value"); finalResult.ret = getInt(pullParser, "value");
} else if ("total_score".equals(pullParser.getName())) { } else if ("total_score".equals(pullParser.getName())) {
finalResult.total_score = getFloat(pullParser, "value"); finalResult.total_score = getFloat(pullParser, "value");
} else if ("xml_result".equals(pullParser.getName())) { } else if ("xml_result".equals(pullParser.getName())) {
// 详细结果 // 详细结果
return parseResult(pullParser); return parseResult(pullParser);
} }
break; break;
case XmlPullParser.END_TAG: case XmlPullParser.END_TAG:
if ("FinalResult".equals(pullParser.getName())) { if ("FinalResult".equals(pullParser.getName())) {
return finalResult; return finalResult;
} }
break; break;
default: default:
break; break;
} }
eventType = pullParser.next(); eventType = pullParser.next();
} }
} catch (XmlPullParserException e) { } catch (XmlPullParserException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
private Result parseResult(XmlPullParser pullParser) { private Result parseResult(XmlPullParser pullParser) {
Result result = null; Result result = null;
// <rec_paper>标签是否已扫描到 // <rec_paper>标签是否已扫描到
boolean rec_paperPassed = false; boolean rec_paperPassed = false;
Sentence sentence = null; Sentence sentence = null;
Word word = null; Word word = null;
Syll syll = null; Syll syll = null;
Phone phone = null; Phone phone = null;
int eventType; int eventType;
try { try {
eventType = pullParser.getEventType(); eventType = pullParser.getEventType();
while (XmlPullParser.END_DOCUMENT != eventType) { while (XmlPullParser.END_DOCUMENT != eventType) {
switch (eventType) { switch (eventType) {
case XmlPullParser.START_TAG: case XmlPullParser.START_TAG:
if ("rec_paper".equals(pullParser.getName())) { if ("rec_paper".equals(pullParser.getName())) {
rec_paperPassed = true; rec_paperPassed = true;
} else if ("read_syllable".equals(pullParser.getName())) { } else if ("read_syllable".equals(pullParser.getName())) {
if (!rec_paperPassed) { if (!rec_paperPassed) {
result = new ReadSyllableResult(); result = new ReadSyllableResult();
} else { } else {
readTotalResult(result, pullParser); readTotalResult(result, pullParser);
} }
} else if ("read_word".equals(pullParser.getName())) { } else if ("read_word".equals(pullParser.getName())) {
if (!rec_paperPassed) { if (!rec_paperPassed) {
result = new ReadWordResult(); result = new ReadWordResult();
String lan = getLanguage(pullParser); String lan = getLanguage(pullParser);
result.language = (null == lan)? "cn": lan; result.language = (null == lan) ? "cn" : lan;
} else { } else {
readTotalResult(result, pullParser); readTotalResult(result, pullParser);
} }
} else if ("read_sentence".equals(pullParser.getName()) || } else if ("read_sentence".equals(pullParser.getName()) ||
"read_chapter".equals(pullParser.getName())) { "read_chapter".equals(pullParser.getName())) {
if (!rec_paperPassed) { if (!rec_paperPassed) {
result = new ReadSentenceResult(); result = new ReadSentenceResult();
String lan = getLanguage(pullParser); String lan = getLanguage(pullParser);
result.language = (null == lan)? "cn": lan; result.language = (null == lan) ? "cn" : lan;
} else { } else {
readTotalResult(result, pullParser); readTotalResult(result, pullParser);
} }
} else if ("sentence".equals(pullParser.getName())) { } else if ("sentence".equals(pullParser.getName())) {
if (null == result.sentences) { if (null == result.sentences) {
result.sentences = new ArrayList<Sentence>(); result.sentences = new ArrayList<Sentence>();
} }
sentence = createSentence(pullParser); sentence = createSentence(pullParser);
} else if ("word".equals(pullParser.getName())) { } else if ("word".equals(pullParser.getName())) {
if (null != sentence && null == sentence.words) { if (null != sentence && null == sentence.words) {
sentence.words = new ArrayList<Word>(); sentence.words = new ArrayList<Word>();
} }
word = createWord(pullParser); word = createWord(pullParser);
} else if ("syll".equals(pullParser.getName())) { } else if ("syll".equals(pullParser.getName())) {
if (null != word && null == word.sylls) { if (null != word && null == word.sylls) {
word.sylls = new ArrayList<Syll>(); word.sylls = new ArrayList<Syll>();
} }
syll = createSyll(pullParser); syll = createSyll(pullParser);
} else if ("phone".equals(pullParser.getName())) { } else if ("phone".equals(pullParser.getName())) {
if (null != syll && null == syll.phones) { if (null != syll && null == syll.phones) {
syll.phones = new ArrayList<Phone>(); syll.phones = new ArrayList<Phone>();
} }
phone = createPhone(pullParser); phone = createPhone(pullParser);
} }
break; break;
case XmlPullParser.END_TAG: case XmlPullParser.END_TAG:
if ("phone".equals(pullParser.getName())) { if ("phone".equals(pullParser.getName())) {
syll.phones.add(phone); syll.phones.add(phone);
} else if ("syll".equals(pullParser.getName())) { } else if ("syll".equals(pullParser.getName())) {
word.sylls.add(syll); word.sylls.add(syll);
} else if ("word".equals(pullParser.getName())) { } else if ("word".equals(pullParser.getName())) {
sentence.words.add(word); sentence.words.add(word);
} else if ("sentence".equals(pullParser.getName())) { } else if ("sentence".equals(pullParser.getName())) {
result.sentences.add(sentence); result.sentences.add(sentence);
} else if ("read_syllable".equals(pullParser.getName()) } else if ("read_syllable".equals(pullParser.getName())
|| "read_word".equals(pullParser.getName()) || "read_word".equals(pullParser.getName())
|| "read_sentence".equals(pullParser.getName())) { || "read_sentence".equals(pullParser.getName())) {
return result; return result;
} }
break; break;
default: default:
break; break;
} }
eventType = pullParser.next(); eventType = pullParser.next();
} }
} catch (XmlPullParserException e) { } catch (XmlPullParserException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
} }
private void readTotalResult(Result result, XmlPullParser pullParser) { private void readTotalResult(Result result, XmlPullParser pullParser) {
result.beg_pos = getInt(pullParser, "beg_pos"); result.beg_pos = getInt(pullParser, "beg_pos");
result.end_pos = getInt(pullParser, "end_pos"); result.end_pos = getInt(pullParser, "end_pos");
result.content = getContent(pullParser); result.content = getContent(pullParser);
result.total_score = getFloat(pullParser, "total_score"); result.total_score = getFloat(pullParser, "total_score");
result.time_len = getInt(pullParser, "time_len"); result.time_len = getInt(pullParser, "time_len");
result.except_info = getExceptInfo(pullParser); result.except_info = getExceptInfo(pullParser);
result.is_rejected = getIsRejected(pullParser); result.is_rejected = getIsRejected(pullParser);
} }
private Phone createPhone(XmlPullParser pullParser) { private Phone createPhone(XmlPullParser pullParser) {
Phone phone; Phone phone;
phone = new Phone(); phone = new Phone();
phone.beg_pos = getInt(pullParser, "beg_pos"); phone.beg_pos = getInt(pullParser, "beg_pos");
phone.end_pos = getInt(pullParser, "end_pos"); phone.end_pos = getInt(pullParser, "end_pos");
phone.content = getContent(pullParser); phone.content = getContent(pullParser);
phone.dp_message = getInt(pullParser, "dp_message"); phone.dp_message = getInt(pullParser, "dp_message");
phone.time_len = getInt(pullParser, "time_len"); phone.time_len = getInt(pullParser, "time_len");
return phone; return phone;
} }
private Syll createSyll(XmlPullParser pullParser) { private Syll createSyll(XmlPullParser pullParser) {
Syll syll; Syll syll;
syll = new Syll(); syll = new Syll();
syll.beg_pos = getInt(pullParser, "beg_pos"); syll.beg_pos = getInt(pullParser, "beg_pos");
syll.end_pos = getInt(pullParser, "end_pos"); syll.end_pos = getInt(pullParser, "end_pos");
syll.content = getContent(pullParser); syll.content = getContent(pullParser);
syll.symbol = getSymbol(pullParser); syll.symbol = getSymbol(pullParser);
syll.dp_message = getInt(pullParser, "dp_message"); syll.dp_message = getInt(pullParser, "dp_message");
syll.time_len = getInt(pullParser, "time_len"); syll.time_len = getInt(pullParser, "time_len");
return syll; return syll;
} }
private Word createWord(XmlPullParser pullParser) { private Word createWord(XmlPullParser pullParser) {
Word word; Word word;
word = new Word(); word = new Word();
word.beg_pos = getInt(pullParser, "beg_pos"); word.beg_pos = getInt(pullParser, "beg_pos");
word.end_pos = getInt(pullParser, "end_pos"); word.end_pos = getInt(pullParser, "end_pos");
word.content = getContent(pullParser); word.content = getContent(pullParser);
word.symbol = getSymbol(pullParser); word.symbol = getSymbol(pullParser);
word.time_len = getInt(pullParser, "time_len"); word.time_len = getInt(pullParser, "time_len");
word.dp_message = getInt(pullParser, "dp_message"); word.dp_message = getInt(pullParser, "dp_message");
word.total_score = getFloat(pullParser, "total_score"); word.total_score = getFloat(pullParser, "total_score");
word.global_index = getInt(pullParser, "global_index"); word.global_index = getInt(pullParser, "global_index");
word.index = getInt(pullParser, "index"); word.index = getInt(pullParser, "index");
return word; return word;
} }
private Sentence createSentence(XmlPullParser pullParser) { private Sentence createSentence(XmlPullParser pullParser) {
Sentence sentence; Sentence sentence;
sentence = new Sentence(); sentence = new Sentence();
sentence.beg_pos = getInt(pullParser, "beg_pos"); sentence.beg_pos = getInt(pullParser, "beg_pos");
sentence.end_pos = getInt(pullParser, "end_pos"); sentence.end_pos = getInt(pullParser, "end_pos");
sentence.content = getContent(pullParser); sentence.content = getContent(pullParser);
sentence.time_len = getInt(pullParser, "time_len"); sentence.time_len = getInt(pullParser, "time_len");
sentence.index = getInt(pullParser, "index"); sentence.index = getInt(pullParser, "index");
sentence.word_count = getInt(pullParser, "word_count"); sentence.word_count = getInt(pullParser, "word_count");
return sentence; return sentence;
} }
private String getLanguage(XmlPullParser pullParser) { private String getLanguage(XmlPullParser pullParser) {
return pullParser.getAttributeValue(null, "lan"); return pullParser.getAttributeValue(null, "lan");
} }
private String getExceptInfo(XmlPullParser pullParser) { private String getExceptInfo(XmlPullParser pullParser) {
return pullParser.getAttributeValue(null, "except_info"); return pullParser.getAttributeValue(null, "except_info");
} }
private boolean getIsRejected(XmlPullParser pullParser) { private boolean getIsRejected(XmlPullParser pullParser) {
String isRejected = pullParser.getAttributeValue(null, "is_rejected"); String isRejected = pullParser.getAttributeValue(null, "is_rejected");
if (null == isRejected) { if (null == isRejected) {
return false; return false;
} }
return Boolean.parseBoolean(isRejected); return Boolean.parseBoolean(isRejected);
} }
private String getSymbol(XmlPullParser pullParser) { private String getSymbol(XmlPullParser pullParser) {
return pullParser.getAttributeValue(null, "symbol"); return pullParser.getAttributeValue(null, "symbol");
} }
private float getFloat(XmlPullParser pullParser, String attrName) { private float getFloat(XmlPullParser pullParser, String attrName) {
String val = pullParser.getAttributeValue(null, attrName); String val = pullParser.getAttributeValue(null, attrName);
if (null == val) { if (null == val) {
return 0f; return 0f;
} }
return Float.parseFloat(val); return Float.parseFloat(val);
} }
private String getContent(XmlPullParser pullParser) { private String getContent(XmlPullParser pullParser) {
return pullParser.getAttributeValue(null, "content"); return pullParser.getAttributeValue(null, "content");
} }
private int getInt(XmlPullParser pullParser, String attrName) { private int getInt(XmlPullParser pullParser, String attrName) {
String val = pullParser.getAttributeValue(null, attrName); String val = pullParser.getAttributeValue(null, attrName);
if (null == val) { if (null == val) {
return 0; return 0;
} }
return Integer.parseInt(val); return Integer.parseInt(val);
} }
} }

View File

@ -15,25 +15,26 @@ import com.iflytek.voicedemo.R;
*/ */
public class IatSettings extends PreferenceActivity implements OnPreferenceChangeListener { public class IatSettings extends PreferenceActivity implements OnPreferenceChangeListener {
public static final String PREFER_NAME = "com.iflytek.setting"; public static final String PREFER_NAME = "com.iflytek.setting";
private EditTextPreference mVadbosPreference; private EditTextPreference mVadbosPreference;
private EditTextPreference mVadeosPreference; private EditTextPreference mVadeosPreference;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(PREFER_NAME); getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
addPreferencesFromResource(R.xml.iat_setting); addPreferencesFromResource(R.xml.iat_setting);
mVadbosPreference = (EditTextPreference)findPreference("iat_vadbos_preference"); mVadbosPreference = (EditTextPreference) findPreference("iat_vadbos_preference");
mVadbosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this,mVadbosPreference,0,10000)); mVadbosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this, mVadbosPreference, 0, 10000));
mVadeosPreference = (EditTextPreference)findPreference("iat_vadeos_preference"); mVadeosPreference = (EditTextPreference) findPreference("iat_vadeos_preference");
mVadeosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this,mVadeosPreference,0,10000)); mVadeosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this, mVadeosPreference, 0, 10000));
} }
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) { @Override
return true; public boolean onPreferenceChange(Preference preference, Object newValue) {
} return true;
}
} }

View File

@ -7,8 +7,8 @@ import android.os.Bundle;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.preference.ListPreference; import android.preference.ListPreference;
import android.preference.Preference; import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.text.InputType; import android.text.InputType;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.Window; import android.view.Window;
@ -17,185 +17,227 @@ import android.widget.Toast;
import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechConstant;
import com.iflytek.voicedemo.R; import com.iflytek.voicedemo.R;
import java.util.HashMap;
/** /**
* 评测设置界面 * 评测设置界面
*/ */
public class IseSettings extends PreferenceActivity { public class IseSettings extends PreferenceActivity {
private final static String PREFER_NAME = "ise_settings"; private final static String PREFER_NAME = "ise_settings";
private ListPreference mLanguagePref; private ListPreference mLanguagePref;
private ListPreference mCategoryPref; private ListPreference mCategoryPref;
private ListPreference mResultLevelPref; private ListPreference mResultLevelPref;
private EditTextPreference mVadBosPref; private EditTextPreference mVadBosPref;
private EditTextPreference mVadEosPref; private EditTextPreference mVadEosPref;
private EditTextPreference mSpeechTimeoutPref; private EditTextPreference mSpeechTimeoutPref;
private Toast mToast; private Toast mToast;
@Override private HashMap<String, String> zhMap = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) { private HashMap<String, String> enMap = new HashMap<>();
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(PREFER_NAME); @Override
addPreferencesFromResource(R.xml.ise_settings); protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
initUI(); getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
} addPreferencesFromResource(R.xml.ise_settings);
initCategoryMap();
initUI();
}
private void initUI() { private void initCategoryMap() {
mLanguagePref = (ListPreference) findPreference(SpeechConstant.LANGUAGE); zhMap.put("read_syllable", "单字");
mCategoryPref = (ListPreference) findPreference(SpeechConstant.ISE_CATEGORY); zhMap.put("read_word", "词语");
mResultLevelPref = (ListPreference) findPreference(SpeechConstant.RESULT_LEVEL); zhMap.put("read_sentence", "句子");
mVadBosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_BOS); zhMap.put("read_chapter", "篇章");
mVadEosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_EOS);
mSpeechTimeoutPref = (EditTextPreference) findPreference(SpeechConstant.KEY_SPEECH_TIMEOUT);
mToast = Toast.makeText(IseSettings.this, "", Toast.LENGTH_LONG); enMap.put("read_word", "词语");
enMap.put("read_sentence", "句子");
enMap.put("read_chapter", "篇章");
enMap.put("simple_expression", "英文情景反应");
enMap.put("read_choice", "英文选择题");
enMap.put("topic", "英文自由题");
enMap.put("retell", "英文复述题");
enMap.put("picture_talk", "英文看图说话");
enMap.put("oral_translation", "英文口头翻译");
}
mLanguagePref.setSummary("当前:" + mLanguagePref.getEntry()); private void initUI() {
mCategoryPref.setSummary("当前:" + mCategoryPref.getEntry()); mLanguagePref = (ListPreference) findPreference(SpeechConstant.LANGUAGE);
mResultLevelPref.setSummary("当前:" + mResultLevelPref.getEntry()); mCategoryPref = (ListPreference) findPreference(SpeechConstant.ISE_CATEGORY);
mVadBosPref.setSummary("当前:" + mVadBosPref.getText() + "ms"); mResultLevelPref = (ListPreference) findPreference(SpeechConstant.RESULT_LEVEL);
mVadEosPref.setSummary("当前:" + mVadEosPref.getText() + "ms"); mVadBosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_BOS);
mVadEosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_EOS);
mSpeechTimeoutPref = (EditTextPreference) findPreference(SpeechConstant.KEY_SPEECH_TIMEOUT);
String speech_timeout = mSpeechTimeoutPref.getText(); mToast = Toast.makeText(IseSettings.this, "", Toast.LENGTH_LONG);
String summary = "当前:" + speech_timeout;
if (!"-1".equals(speech_timeout)) {
summary += "ms";
}
mSpeechTimeoutPref.setSummary(summary);
mLanguagePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { mLanguagePref.setSummary("当前:" + mLanguagePref.getEntry());
mCategoryPref.setSummary("当前:" + mCategoryPref.getEntry());
mResultLevelPref.setSummary("当前:" + mResultLevelPref.getEntry());
mVadBosPref.setSummary("当前:" + mVadBosPref.getText() + "ms");
mVadEosPref.setSummary("当前:" + mVadEosPref.getText() + "ms");
@Override String speech_timeout = mSpeechTimeoutPref.getText();
public boolean onPreferenceChange(Preference preference, Object newValue) { String summary = "当前:" + speech_timeout;
if ("zh_cn".equals(newValue.toString())) { if (!"-1".equals(speech_timeout)) {
if ("plain".equals(mResultLevelPref.getValue())) { summary += "ms";
showTip("汉语评测结果格式不支持plain设置"); }
return false; mSpeechTimeoutPref.setSummary(summary);
}
} else {
if ("read_syllable".equals(mCategoryPref.getValue())) {
showTip("英语评测不支持单字");
return false;
}
}
int newValueIndex = mLanguagePref.findIndexOfValue(newValue.toString()); mLanguagePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
String newEntry = (String) mLanguagePref.getEntries()[newValueIndex];
mLanguagePref.setSummary("当前:" + newEntry);
return true;
}
});
mCategoryPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
@Override String categoryValue = mCategoryPref.getValue();
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ("en_us".equals(mLanguagePref.getValue()) && "read_syllable".equals(newValue.toString())) {
showTip("英语评测不支持单字,请选其他项");
return false;
}
int newValueIndex = mCategoryPref.findIndexOfValue(newValue.toString()); if ("zh_cn".equals(newValue.toString())) {
String newEntry = (String) mCategoryPref.getEntries()[newValueIndex]; // 中文
mCategoryPref.setSummary("当前:" + newEntry); if ("plain".equals(mResultLevelPref.getValue())) {
return true; showTip("汉语评测结果格式不支持plain设置");
} return false;
}); }
if (!zhMap.containsKey(categoryValue)) {
showTip("中文评测不支持" + enMap.get(categoryValue));
return false;
}
} else {
// 英文
if (!enMap.containsKey(categoryValue)) {
showTip("英语评测不支持" + zhMap.get(categoryValue));
return false;
}
}
mResultLevelPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { int newValueIndex = mLanguagePref.findIndexOfValue(newValue.toString());
String newEntry = (String) mLanguagePref.getEntries()[newValueIndex];
mLanguagePref.setSummary("当前:" + newEntry);
return true;
}
});
@Override mCategoryPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ("zh_cn".equals(mLanguagePref.getValue()) && "plain".equals(newValue.toString())) {
showTip("汉语评测不支持plain请选其他项");
return false;
}
mResultLevelPref.setSummary("当前:" + newValue.toString()); @Override
return true; public boolean onPreferenceChange(Preference preference, Object newValue) {
} String categoryValue = newValue.toString();
});
mVadBosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER); if ("en_us".equals(mLanguagePref.getValue())) {
mVadBosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { if (!enMap.containsKey(categoryValue)) {
showTip("英语评测不支持" + zhMap.get(categoryValue) + ",请选其他项");
return false;
}
}
if ("zh_cn".equals(mLanguagePref.getValue())) {
if (!zhMap.containsKey(categoryValue)) {
showTip("中文评测不支持" + enMap.get(categoryValue) + ",请选其他项");
return false;
}
}
@Override int newValueIndex = mCategoryPref.findIndexOfValue(newValue.toString());
public boolean onPreferenceChange(Preference preference, Object newValue) { String newEntry = (String) mCategoryPref.getEntries()[newValueIndex];
int bos; mCategoryPref.setSummary("当前:" + newEntry);
try { return true;
bos = Integer.parseInt(newValue.toString()); }
} catch (Exception e) { });
showTip("无效输入!");
return false;
}
if (bos < 0 || bos > 30000) {
showTip("取值范围为0~30000");
return false;
}
mVadBosPref.setSummary("当前:" + bos + "ms"); mResultLevelPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
return true;
}
});
mVadEosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER); @Override
mVadEosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) {
if ("zh_cn".equals(mLanguagePref.getValue()) && "plain".equals(newValue.toString())) {
showTip("汉语评测不支持plain请选其他项");
return false;
}
@Override mResultLevelPref.setSummary("当前:" + newValue.toString());
public boolean onPreferenceChange(Preference preference, Object newValue) { return true;
int eos; }
try { });
eos = Integer.parseInt(newValue.toString());
} catch (Exception e) {
showTip("无效输入!");
return false;
}
if (eos < 0 || eos > 30000) {
showTip("取值范围为0~30000");
return false;
}
mVadEosPref.setSummary("当前:" + eos + "ms"); mVadBosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
return true; mVadBosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
}
});
mSpeechTimeoutPref.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED|InputType.TYPE_CLASS_NUMBER); @Override
mSpeechTimeoutPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) {
int bos;
try {
bos = Integer.parseInt(newValue.toString());
} catch (Exception e) {
showTip("无效输入!");
return false;
}
if (bos < 0 || bos > 30000) {
showTip("取值范围为0~30000");
return false;
}
@Override mVadBosPref.setSummary("当前:" + bos + "ms");
public boolean onPreferenceChange(Preference preference, Object newValue) { return true;
int speech_timeout; }
try { });
speech_timeout = Integer.parseInt(newValue.toString());
} catch (Exception e) {
showTip("无效输入!");
return false;
}
if (speech_timeout < -1) { mVadEosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
showTip("必须大于等于-1"); mVadEosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
return false;
}
if (speech_timeout == -1) { @Override
mSpeechTimeoutPref.setSummary("当前:-1"); public boolean onPreferenceChange(Preference preference, Object newValue) {
} else { int eos;
mSpeechTimeoutPref.setSummary("当前:" + speech_timeout + "ms"); try {
} eos = Integer.parseInt(newValue.toString());
} catch (Exception e) {
showTip("无效输入!");
return false;
}
if (eos < 0 || eos > 30000) {
showTip("取值范围为0~30000");
return false;
}
return true; mVadEosPref.setSummary("当前:" + eos + "ms");
} return true;
}); }
} });
private void showTip(String str) { mSpeechTimeoutPref.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_CLASS_NUMBER);
if(!TextUtils.isEmpty(str)) { mSpeechTimeoutPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
mToast.setText(str);
mToast.show(); @Override
} public boolean onPreferenceChange(Preference preference, Object newValue) {
} int speech_timeout;
try {
speech_timeout = Integer.parseInt(newValue.toString());
} catch (Exception e) {
showTip("无效输入!");
return false;
}
if (speech_timeout < -1) {
showTip("必须大于等于-1");
return false;
}
if (speech_timeout == -1) {
mSpeechTimeoutPref.setSummary("当前:-1");
} else {
mSpeechTimeoutPref.setSummary("当前:" + speech_timeout + "ms");
}
return true;
}
});
}
private void showTip(String str) {
if (!TextUtils.isEmpty(str)) {
mToast.cancel();
mToast.setText(str);
mToast.show();
}
}
} }

View File

@ -16,34 +16,34 @@ import com.iflytek.voicedemo.R;
*/ */
public class TtsSettings extends PreferenceActivity implements OnPreferenceChangeListener { public class TtsSettings extends PreferenceActivity implements OnPreferenceChangeListener {
public static final String PREFER_NAME = "com.iflytek.setting"; public static final String PREFER_NAME = "com.iflytek.setting";
private EditTextPreference mSpeedPreference; private EditTextPreference mSpeedPreference;
private EditTextPreference mPitchPreference; private EditTextPreference mPitchPreference;
private EditTextPreference mVolumePreference; private EditTextPreference mVolumePreference;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 指定保存文件名字 // 指定保存文件名字
getPreferenceManager().setSharedPreferencesName(PREFER_NAME); getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
addPreferencesFromResource(R.xml.tts_setting); addPreferencesFromResource(R.xml.tts_setting);
mSpeedPreference = (EditTextPreference)findPreference("speed_preference"); mSpeedPreference = (EditTextPreference) findPreference("speed_preference");
mSpeedPreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this,mSpeedPreference,0,200)); mSpeedPreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this, mSpeedPreference, 0, 200));
mPitchPreference = (EditTextPreference)findPreference("pitch_preference"); mPitchPreference = (EditTextPreference) findPreference("pitch_preference");
mPitchPreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this,mPitchPreference,0,100)); mPitchPreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this, mPitchPreference, 0, 100));
mVolumePreference = (EditTextPreference)findPreference("volume_preference"); mVolumePreference = (EditTextPreference) findPreference("volume_preference");
mVolumePreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this,mVolumePreference,0,100)); mVolumePreference.getEditText().addTextChangedListener(new SettingTextWatcher(TtsSettings.this, mVolumePreference, 0, 100));
} }
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
return true; return true;
} }
} }

View File

@ -1,18 +1,15 @@
package com.iflytek.speech.setting; package com.iflytek.speech.setting;
import android.os.Bundle; import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.preference.ListPreference; import android.preference.ListPreference;
import android.preference.Preference; import android.preference.Preference;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.support.annotation.Nullable;
import android.view.Window; import android.view.Window;
import com.iflytek.cloud.SpeechConstant; import androidx.annotation.Nullable;
import com.iflytek.voicedemo.R;
import java.util.List; import com.iflytek.voicedemo.R;
/** /**
* @author hjyu * @author hjyu
@ -33,7 +30,7 @@ public class UrlSettings extends PreferenceActivity implements Preference.OnPref
getPreferenceManager().setSharedPreferencesName(PREFER_NAME); getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
addPreferencesFromResource(R.xml.url_setting); addPreferencesFromResource(R.xml.url_setting);
url_preference = (ListPreference)findPreference("url_preference"); url_preference = (ListPreference) findPreference("url_preference");
url_preference.setSummary("当前:" + url_preference.getEntry()); url_preference.setSummary("当前:" + url_preference.getEntry());
url_preference.setOnPreferenceChangeListener(this); url_preference.setOnPreferenceChangeListener(this);

View File

@ -5,19 +5,19 @@ import android.graphics.Rect;
/** /**
* @author MatrixCV * @author MatrixCV
* FaceRect是用于表示人脸检测的结果其中包括了 人脸的角度得分检测框位置关键点 * FaceRect是用于表示人脸检测的结果其中包括了 人脸的角度得分检测框位置关键点
*/ */
public class FaceRect { public class FaceRect {
public float score; public float score;
public Rect bound = new Rect(); public Rect bound = new Rect();
public Point point[]; public Point point[];
public Rect raw_bound = new Rect(); public Rect raw_bound = new Rect();
public Point raw_point[]; public Point raw_point[];
@Override @Override
public String toString() { public String toString() {
return bound.toString(); return bound.toString();
} }
} }

View File

@ -3,6 +3,8 @@ package com.iflytek.speech.util;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
@ -13,257 +15,263 @@ import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
import android.media.ExifInterface; import android.media.ExifInterface;
import android.net.Uri; import android.net.Uri;
import android.os.Environment; import android.os.Build;
import android.provider.MediaStore; import android.provider.MediaStore;
import androidx.core.content.FileProvider;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class FaceUtil { public class FaceUtil {
public final static int REQUEST_PICTURE_CHOOSE = 1; public final static int REQUEST_PICTURE_CHOOSE = 1;
public final static int REQUEST_CAMERA_IMAGE = 2; public final static int REQUEST_CAMERA_IMAGE = 2;
public final static int REQUEST_CROP_IMAGE = 3; public final static int REQUEST_CROP_IMAGE = 3;
/***
* 裁剪图片
* @param activity Activity
* @param uri 图片的Uri
*/
public static void cropPicture(Activity activity, Uri uri) {
Intent innerIntent = new Intent("com.android.camera.action.CROP");
innerIntent.setDataAndType(uri, "image/*");
innerIntent.putExtra("crop", "true");// 才能出剪辑的小方框不然没有剪辑功能只能选取图片
innerIntent.putExtra("aspectX", 1); // 放大缩小比例的X
innerIntent.putExtra("aspectY", 1);// 放大缩小比例的X 这里的比例为 1:1
innerIntent.putExtra("outputX", 320); //这个是限制输出图片大小
innerIntent.putExtra("outputY", 320);
innerIntent.putExtra("return-data", true);
// 切图大小不足输出无黑框
innerIntent.putExtra("scale", true);
innerIntent.putExtra("scaleUpIfNeeded", true);
File imageFile = new File(getImagePath(activity.getApplicationContext()));
innerIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
innerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
activity.startActivityForResult(innerIntent, REQUEST_CROP_IMAGE);
}
/** public static Uri parseUri(Context context, File file) {
* 保存裁剪的图片的路径 Uri imageUri = Uri.fromFile(file);
* @return if (Build.VERSION.SDK_INT >= 24) {
*/ imageUri = FileProvider.getUriForFile(
public static String getImagePath(Context context){ context,
String path; context.getPackageName() + ".fileprovider",
file
);
}
return imageUri;
}
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { /***
path = context.getFilesDir().getAbsolutePath(); * 裁剪图片
} else { * @param activity Activity
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/msc/"; * @param uri 图片的Uri
} */
public static void cropPicture(Activity activity, Uri uri) {
Intent innerIntent = new Intent("com.android.camera.action.CROP");
innerIntent.setDataAndType(uri, "image/*");
innerIntent.putExtra("crop", "true");// 才能出剪辑的小方框不然没有剪辑功能只能选取图片
innerIntent.putExtra("aspectX", 1); // 放大缩小比例的X
innerIntent.putExtra("aspectY", 1);// 放大缩小比例的X 这里的比例为 1:1
innerIntent.putExtra("outputX", 320); //这个是限制输出图片大小
innerIntent.putExtra("outputY", 320);
innerIntent.putExtra("return-data", false);
// 切图大小不足输出无黑框
innerIntent.putExtra("scale", true);
innerIntent.putExtra("scaleUpIfNeeded", true);
File imageFile = new File(getImagePath(activity.getApplicationContext()));
imageFile.delete();
Uri cropUri = parseUri(activity, imageFile);
innerIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
innerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
if(!path.endsWith("/")) { List<ResolveInfo> resolveInfos = activity.getPackageManager()
path += "/"; .queryIntentActivities(innerIntent, PackageManager.MATCH_DEFAULT_ONLY);
} for (ResolveInfo resolveInfo : resolveInfos) {
activity.grantUriPermission(activity.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.grantUriPermission(resolveInfo.activityInfo.packageName, cropUri,
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
}
innerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
innerIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
activity.startActivityForResult(innerIntent, REQUEST_CROP_IMAGE);
}
File folder = new File(path); /**
if (folder != null && !folder.exists()) { * 保存裁剪的图片的路径
folder.mkdirs(); *
} * @return
path += "ifd.jpg"; */
return path; public static String getImagePath(Context context) {
} String path = context.getExternalFilesDir("msc").getAbsolutePath();
if (!path.endsWith("/")) {
path += "/";
}
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
path += "ifd.jpg";
return path;
}
/** /**
* 读取图片属性旋转的角度 * 读取图片属性旋转的角度
* *
* @param path 图片绝对路径 * @param path 图片绝对路径
* @return degree 旋转角度 * @return degree 旋转角度
*/ */
public static int readPictureDegree(String path) { public static int readPictureDegree(String path) {
int degree = 0; int degree = 0;
try { try {
ExifInterface exifInterface = new ExifInterface(path); ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt( int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL); ExifInterface.ORIENTATION_NORMAL);
switch (orientation) { switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90; degree = 90;
break; break;
case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180; degree = 180;
break; break;
case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270; degree = 270;
break; break;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return degree; return degree;
} }
/** /**
* 旋转图片 * 旋转图片
* *
* @param angle 旋转角度 * @param angle 旋转角度
* @param bitmap 原图 * @param bitmap 原图
* @return bitmap 旋转后的图片 * @return bitmap 旋转后的图片
*/ */
public static Bitmap rotateImage(int angle, Bitmap bitmap) { public static Bitmap rotateImage(int angle, Bitmap bitmap) {
// 图片旋转矩阵 // 图片旋转矩阵
Matrix matrix = new Matrix(); Matrix matrix = new Matrix();
matrix.postRotate(angle); matrix.postRotate(angle);
// 得到旋转后的图片 // 得到旋转后的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true); bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap; return resizedBitmap;
} }
/** /**
* 在指定画布上将人脸框出来 * 在指定画布上将人脸框出来
* *
* @param canvas 给定的画布 * @param canvas 给定的画布
* @param face 需要绘制的人脸信息 * @param face 需要绘制的人脸信息
* @param width 原图宽 * @param width 原图宽
* @param height 原图高 * @param height 原图高
* @param frontCamera 是否为前置摄像头如为前置摄像头需左右对称 * @param frontCamera 是否为前置摄像头如为前置摄像头需左右对称
* @param DrawOriRect 可绘制原始框也可以只画四个角 * @param DrawOriRect 可绘制原始框也可以只画四个角
*/ */
static public void drawFaceRect(Canvas canvas, FaceRect face, int width, int height, boolean frontCamera, boolean DrawOriRect) { static public void drawFaceRect(Canvas canvas, FaceRect face, int width, int height, boolean frontCamera, boolean DrawOriRect) {
if(canvas == null) { if (canvas == null) {
return; return;
} }
Paint paint = new Paint(); Paint paint = new Paint();
paint.setColor(Color.rgb(255, 203, 15)); paint.setColor(Color.rgb(255, 203, 15));
int len = (face.bound.bottom - face.bound.top) / 8; int len = (face.bound.bottom - face.bound.top) / 8;
if (len / 8 >= 2) paint.setStrokeWidth(len / 8); if (len / 8 >= 2) paint.setStrokeWidth(len / 8);
else paint.setStrokeWidth(2); else paint.setStrokeWidth(2);
Rect rect = face.bound; Rect rect = face.bound;
if(frontCamera) { if (frontCamera) {
int top = rect.top; int top = rect.top;
rect.top = width - rect.bottom; rect.top = width - rect.bottom;
rect.bottom = width - top; rect.bottom = width - top;
} }
if (DrawOriRect) { if (DrawOriRect) {
paint.setStyle(Style.STROKE); paint.setStyle(Style.STROKE);
canvas.drawRect(rect, paint); canvas.drawRect(rect, paint);
} else { } else {
int drawl = rect.left - len; int drawl = rect.left - len;
int drawr = rect.right + len; int drawr = rect.right + len;
int drawu = rect.top - len; int drawu = rect.top - len;
int drawd = rect.bottom + len; int drawd = rect.bottom + len;
canvas.drawLine(drawl,drawd,drawl,drawd-len, paint); canvas.drawLine(drawl, drawd, drawl, drawd - len, paint);
canvas.drawLine(drawl,drawd,drawl+len,drawd, paint); canvas.drawLine(drawl, drawd, drawl + len, drawd, paint);
canvas.drawLine(drawr,drawd,drawr,drawd-len, paint); canvas.drawLine(drawr, drawd, drawr, drawd - len, paint);
canvas.drawLine(drawr,drawd,drawr-len,drawd, paint); canvas.drawLine(drawr, drawd, drawr - len, drawd, paint);
canvas.drawLine(drawl,drawu,drawl,drawu+len, paint); canvas.drawLine(drawl, drawu, drawl, drawu + len, paint);
canvas.drawLine(drawl,drawu,drawl+len,drawu, paint); canvas.drawLine(drawl, drawu, drawl + len, drawu, paint);
canvas.drawLine(drawr,drawu,drawr,drawu+len, paint); canvas.drawLine(drawr, drawu, drawr, drawu + len, paint);
canvas.drawLine(drawr,drawu,drawr-len,drawu, paint); canvas.drawLine(drawr, drawu, drawr - len, drawu, paint);
} }
if (face.point != null) { if (face.point != null) {
for (Point p : face.point) for (Point p : face.point) {
{ if (frontCamera) {
if(frontCamera) { p.y = width - p.y;
p.y = width - p.y; }
} canvas.drawPoint(p.x, p.y, paint);
canvas.drawPoint(p.x, p.y, paint); }
} }
} }
}
/** /**
* 将矩形随原图顺时针旋转90度 * 将矩形随原图顺时针旋转90度
* *
* @param r * @param r 待旋转的矩形
* 待旋转的矩形 * @param width 输入矩形对应的原图宽
* * @param height 输入矩形对应的原图高
* @param width * @return 旋转后的矩形
* 输入矩形对应的原图宽 */
* static public Rect RotateDeg90(Rect r, int width, int height) {
* @param height int left = r.left;
* 输入矩形对应的原图高 r.left = height - r.bottom;
* r.bottom = r.right;
* @return r.right = height - r.top;
* 旋转后的矩形 r.top = left;
*/ return r;
static public Rect RotateDeg90(Rect r, int width, int height) { }
int left = r.left;
r.left = height- r.bottom;
r.bottom= r.right;
r.right = height- r.top;
r.top = left;
return r;
}
/** /**
* 将点随原图顺时针旋转90度 * 将点随原图顺时针旋转90度
* @param p *
* 待旋转的点 * @param p 待旋转的点
* * @param width 输入点对应的原图宽
* @param width * @param height 输入点对应的原图宽
* 输入点对应的原图宽 * @return 旋转后的点
* */
* @param height static public Point RotateDeg90(Point p, int width, int height) {
* 输入点对应的原图宽 int x = p.x;
* p.x = height - p.y;
* @return p.y = x;
* 旋转后的点 return p;
*/ }
static public Point RotateDeg90(Point p, int width, int height) {
int x = p.x;
p.x = height - p.y;
p.y = x;
return p;
}
public static int getNumCores() { public static int getNumCores() {
class CpuFilter implements FileFilter { class CpuFilter implements FileFilter {
@Override @Override
public boolean accept(File pathname) { public boolean accept(File pathname) {
if(Pattern.matches("cpu[0-9]", pathname.getName())) { if (Pattern.matches("cpu[0-9]", pathname.getName())) {
return true; return true;
} }
return false; return false;
} }
} }
try { try {
File dir = new File("/sys/devices/system/cpu/"); File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter()); File[] files = dir.listFiles(new CpuFilter());
return files.length; return files.length;
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return 1; return 1;
} }
} }
/** /**
* 保存Bitmap至本地 * 保存Bitmap至本地
* @param Bitmap */
*/ public static void saveBitmapToFile(Context context, Bitmap bmp) {
public static void saveBitmapToFile(Context context,Bitmap bmp){ String file_path = getImagePath(context);
String file_path = getImagePath(context); File file = new File(file_path);
File file = new File(file_path); FileOutputStream fOut;
FileOutputStream fOut; try {
try { fOut = new FileOutputStream(file);
fOut = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush();
fOut.flush(); fOut.close();
fOut.close(); } catch (FileNotFoundException e) {
} catch (FileNotFoundException e) { e.printStackTrace();
e.printStackTrace(); } catch (IOException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); }
} }
}
} }

View File

@ -1,144 +1,144 @@
package com.iflytek.speech.util; package com.iflytek.speech.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.json.JSONArray; import android.content.Context;
import org.json.JSONObject;
import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SpeechUtility;
import android.content.Context; import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/** /**
* 功能性函数扩展类 * 功能性函数扩展类
*/ */
public class FucUtil { public class FucUtil {
/** /**
* 读取asset目录下文件 * 读取asset目录下文件
* @return content *
*/ * @return content
public static String readFile(Context mContext,String file,String code) */
{ public static String readFile(Context mContext, String file, String code) {
int len = 0; int len = 0;
byte []buf = null; byte[] buf = null;
String result = ""; String result = "";
try { try {
InputStream in = mContext.getAssets().open(file); InputStream in = mContext.getAssets().open(file);
len = in.available(); len = in.available();
buf = new byte[len]; buf = new byte[len];
in.read(buf, 0, len); in.read(buf, 0, len);
result = new String(buf,code); result = new String(buf, code);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
} }
/**
* 将字节缓冲区按照固定大小进行分割成数组
* @param buffer 缓冲区
* @param length 缓冲区大小
* @param spsize 切割块大小
* @return
*/
public static ArrayList<byte[]> splitBuffer(byte[] buffer,int length,int spsize)
{
ArrayList<byte[]> array = new ArrayList<byte[]>();
if(spsize <= 0 || length <= 0 || buffer == null || buffer.length < length)
return array;
int size = 0;
while(size < length)
{
int left = length - size;
if(spsize < left)
{
byte[] sdata = new byte[spsize];
System.arraycopy(buffer,size,sdata,0,spsize);
array.add(sdata);
size += spsize;
}else
{
byte[] sdata = new byte[left];
System.arraycopy(buffer,size,sdata,0,left);
array.add(sdata);
size += left;
}
}
return array;
}
/**
* 获取语记是否包含离线听写资源如未包含跳转至资源下载页面
*1.PLUS_LOCAL_ALL: 本地所有资源
2.PLUS_LOCAL_ASR: 本地识别资源
3.PLUS_LOCAL_TTS: 本地合成资源
*/
public static String checkLocalResource(){
String resource = SpeechUtility.getUtility().getParameter(SpeechConstant.PLUS_LOCAL_ASR);
try {
JSONObject result = new JSONObject(resource);
int ret = result.getInt(SpeechUtility.TAG_RESOURCE_RET);
switch (ret) {
case ErrorCode.SUCCESS:
JSONArray asrArray = result.getJSONObject("result").optJSONArray("asr");
if (asrArray != null) {
int i = 0;
// 查询否包含离线听写资源
for (; i < asrArray.length(); i++) {
if("iat".equals(asrArray.getJSONObject(i).get(SpeechConstant.DOMAIN))){
//asrArray中包含语言方言字段后续会增加支持方言的本地听写
//"accent": "mandarin","language": "zh_cn"
break;
}
}
if (i >= asrArray.length()) {
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR); /**
return "没有听写资源,跳转至资源下载页面"; * 将字节缓冲区按照固定大小进行分割成数组
} *
}else { * @param buffer 缓冲区
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR); * @param length 缓冲区大小
return "没有听写资源,跳转至资源下载页面"; * @param spsize 切割块大小
} * @return
break; */
case ErrorCode.ERROR_VERSION_LOWER: public static ArrayList<byte[]> splitBuffer(byte[] buffer, int length, int spsize) {
return "语记版本过低,请更新后使用本地功能"; ArrayList<byte[]> array = new ArrayList<byte[]>();
case ErrorCode.ERROR_INVALID_RESULT: if (spsize <= 0 || length <= 0 || buffer == null || buffer.length < length)
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR); return array;
return "获取结果出错,跳转至资源下载页面"; int size = 0;
case ErrorCode.ERROR_SYSTEM_PREINSTALL: while (size < length) {
default: int left = length - size;
break; if (spsize < left) {
} byte[] sdata = new byte[spsize];
} catch (Exception e) { System.arraycopy(buffer, size, sdata, 0, spsize);
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR); array.add(sdata);
return "获取结果出错,跳转至资源下载页面"; size += spsize;
} } else {
return ""; byte[] sdata = new byte[left];
} System.arraycopy(buffer, size, sdata, 0, left);
array.add(sdata);
size += left;
}
}
return array;
}
/** /**
* 读取asset目录下音频文件 * 获取语记是否包含离线听写资源如未包含跳转至资源下载页面
* * 1.PLUS_LOCAL_ALL: 本地所有资源
* @return 二进制文件数据 * 2.PLUS_LOCAL_ASR: 本地识别资源
*/ * 3.PLUS_LOCAL_TTS: 本地合成资源
public static byte[] readAudioFile(Context context, String filename) { */
try { public static String checkLocalResource() {
InputStream ins = context.getAssets().open(filename); String resource = SpeechUtility.getUtility().getParameter(SpeechConstant.PLUS_LOCAL_ASR);
byte[] data = new byte[ins.available()]; try {
JSONObject result = new JSONObject(resource);
int ret = result.getInt(SpeechUtility.TAG_RESOURCE_RET);
switch (ret) {
case ErrorCode.SUCCESS:
JSONArray asrArray = result.getJSONObject("result").optJSONArray("asr");
if (asrArray != null) {
int i = 0;
// 查询否包含离线听写资源
for (; i < asrArray.length(); i++) {
if ("iat".equals(asrArray.getJSONObject(i).get(SpeechConstant.DOMAIN))) {
//asrArray中包含语言方言字段后续会增加支持方言的本地听写
//"accent": "mandarin","language": "zh_cn"
break;
}
}
if (i >= asrArray.length()) {
ins.read(data); SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR);
ins.close(); return "没有听写资源,跳转至资源下载页面";
}
} else {
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR);
return "没有听写资源,跳转至资源下载页面";
}
break;
case ErrorCode.ERROR_VERSION_LOWER:
return "语记版本过低,请更新后使用本地功能";
case ErrorCode.ERROR_INVALID_RESULT:
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR);
return "获取结果出错,跳转至资源下载页面";
case ErrorCode.ERROR_SYSTEM_PREINSTALL:
default:
break;
}
} catch (Exception e) {
SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_ASR);
return "获取结果出错,跳转至资源下载页面";
}
return "";
}
return data; /**
} catch (IOException e) { * 读取asset目录下音频文件
// TODO Auto-generated catch block *
e.printStackTrace(); * @return 二进制文件数据
} */
public static byte[] readAudioFile(Context context, String filename) {
try {
InputStream ins = context.getAssets().open(filename);
byte[] data = new byte[ins.available()];
return null; ins.read(data);
} ins.close();
return data;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} }

View File

@ -4,116 +4,170 @@ import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONTokener; import org.json.JSONTokener;
import android.util.Log;
/** /**
* Json结果解析类 * Json结果解析类
*/ */
public class JsonParser { public class JsonParser {
public static String parseIatResult(String json) { public static String parseIatResult(String json) {
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
try { try {
JSONTokener tokener = new JSONTokener(json); JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener); JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws"); JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) { for (int i = 0; i < words.length(); i++) {
// 转写结果词默认使用第一个结果 // 转写结果词默认使用第一个结果
JSONArray items = words.getJSONObject(i).getJSONArray("cw"); JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0); JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w")); ret.append(obj.getString("w"));
// 如果需要多候选结果解析数组其他字段 // 如果需要多候选结果解析数组其他字段
// for(int j = 0; j < items.length(); j++) // for(int j = 0; j < items.length(); j++)
// { // {
// JSONObject obj = items.getJSONObject(j); // JSONObject obj = items.getJSONObject(j);
// ret.append(obj.getString("w")); // ret.append(obj.getString("w"));
// } // }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return ret.toString(); return ret.toString();
} }
public static String parseGrammarResult(String json) { public static String parseGrammarResult(String json, String engType) {
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
try { try {
JSONTokener tokener = new JSONTokener(json); JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener); JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws"); JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) { // 云端和本地结果分情况解析
JSONArray items = words.getJSONObject(i).getJSONArray("cw"); if ("cloud".equals(engType)) {
for(int j = 0; j < items.length(); j++) for (int i = 0; i < words.length(); i++) {
{ JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(j); for (int j = 0; j < items.length(); j++) {
if(obj.getString("w").contains("nomatch")) JSONObject obj = items.getJSONObject(j);
{ if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果."); ret.append("没有匹配结果.");
return ret.toString(); return ret.toString();
} }
ret.append("【结果】" + obj.getString("w")); ret.append("【结果】" + obj.getString("w"));
ret.append("【置信度】" + obj.getInt("sc")); ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n"); ret.append("\n");
} }
} }
} catch (Exception e) { } else if ("local".equals(engType)) {
e.printStackTrace(); ret.append("【结果】");
ret.append("没有匹配结果."); for (int i = 0; i < words.length(); i++) {
} JSONObject wsItem = words.getJSONObject(i);
return ret.toString(); JSONArray items = wsItem.getJSONArray("cw");
} if ("<contact>".equals(wsItem.getString("slot"))) {
// 可能会有多个联系人供选择用中括号括起来这些候选项具有相同的置信度
ret.append("");
for (int j = 0; j < items.length(); j++) {
JSONObject obj = items.getJSONObject(j);
if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append(obj.getString("w")).append("|");
}
ret.setCharAt(ret.length() - 1, '】');
} else {
//本地多候选按照置信度高低排序一般选取第一个结果即可
JSONObject obj = items.getJSONObject(0);
if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append(obj.getString("w"));
}
}
ret.append("【置信度】" + joResult.getInt("sc"));
ret.append("\n");
}
public static String parseLocalGrammarResult(String json) { } catch (Exception e) {
StringBuffer ret = new StringBuffer(); e.printStackTrace();
try { ret.append("没有匹配结果.");
JSONTokener tokener = new JSONTokener(json); }
JSONObject joResult = new JSONObject(tokener); return ret.toString();
}
JSONArray words = joResult.getJSONArray("ws"); public static String parseGrammarResult(String json) {
for (int i = 0; i < words.length(); i++) { StringBuffer ret = new StringBuffer();
JSONArray items = words.getJSONObject(i).getJSONArray("cw"); try {
for(int j = 0; j < items.length(); j++) JSONTokener tokener = new JSONTokener(json);
{ JSONObject joResult = new JSONObject(tokener);
JSONObject obj = items.getJSONObject(j);
if(obj.getString("w").contains("nomatch"))
{
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append("【结果】" + obj.getString("w"));
ret.append("\n");
}
}
ret.append("【置信度】" + joResult.optInt("sc"));
} catch (Exception e) { JSONArray words = joResult.getJSONArray("ws");
e.printStackTrace(); for (int i = 0; i < words.length(); i++) {
ret.append("没有匹配结果."); JSONArray items = words.getJSONObject(i).getJSONArray("cw");
} for (int j = 0; j < items.length(); j++) {
return ret.toString(); JSONObject obj = items.getJSONObject(j);
} if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append("【结果】" + obj.getString("w"));
ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
public static String parseTransResult(String json,String key) { public static String parseLocalGrammarResult(String json) {
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
try { try {
JSONTokener tokener = new JSONTokener(json); JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener); JSONObject joResult = new JSONObject(tokener);
String errorCode = joResult.optString("ret");
if(!errorCode.equals("0")) { JSONArray words = joResult.getJSONArray("ws");
return joResult.optString("errmsg"); for (int i = 0; i < words.length(); i++) {
} JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject transResult = joResult.optJSONObject("trans_result"); for (int j = 0; j < items.length(); j++) {
ret.append(transResult.optString(key)); JSONObject obj = items.getJSONObject(j);
if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append("【结果】" + obj.getString("w"));
ret.append("\n");
}
}
ret.append("【置信度】" + joResult.optInt("sc"));
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
public static String parseTransResult(String json, String key) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
String errorCode = joResult.optString("ret");
if (!errorCode.equals("0")) {
return joResult.optString("errmsg");
}
JSONObject transResult = joResult.optJSONObject("trans_result");
ret.append(transResult.optString(key));
/*JSONArray words = joResult.getJSONArray("results"); /*JSONArray words = joResult.getJSONArray("results");
for (int i = 0; i < words.length(); i++) { for (int i = 0; i < words.length(); i++) {
JSONObject obj = words.getJSONObject(i); JSONObject obj = words.getJSONObject(i);
ret.append(obj.getString(key)); ret.append(obj.getString(key));
}*/ }*/
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return ret.toString(); return ret.toString();
} }
} }

View File

@ -1,6 +1,5 @@
package com.iflytek.speech.util; package com.iflytek.speech.util;
import java.util.regex.Pattern;
import android.content.Context; import android.content.Context;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.text.Editable; import android.text.Editable;
@ -8,63 +7,65 @@ import android.text.TextUtils;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.widget.Toast; import android.widget.Toast;
import java.util.regex.Pattern;
/** /**
* 输入框输入范围控制 * 输入框输入范围控制
*/ */
public class SettingTextWatcher implements TextWatcher { public class SettingTextWatcher implements TextWatcher {
private int editStart ; private int editStart;
private int editCount ; private int editCount;
private EditTextPreference mEditTextPreference; private EditTextPreference mEditTextPreference;
int minValue;//最小值 int minValue;//最小值
int maxValue;//最大值 int maxValue;//最大值
private Context mContext; private Context mContext;
public SettingTextWatcher(Context context,EditTextPreference e,int min, int max) { public SettingTextWatcher(Context context, EditTextPreference e, int min, int max) {
mContext = context; mContext = context;
mEditTextPreference = e; mEditTextPreference = e;
minValue = min; minValue = min;
maxValue = max; maxValue = max;
} }
@Override @Override
public void onTextChanged(CharSequence s, int start, int before, int count) { public void onTextChanged(CharSequence s, int start, int before, int count) {
// Log.e("demo", "onTextChanged start:"+start+" count:"+count+" before:"+before); // Log.e("demo", "onTextChanged start:"+start+" count:"+count+" before:"+before);
editStart = start; editStart = start;
editCount = count; editCount = count;
} }
@Override @Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) { public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Log.e("demo", "beforeTextChanged start:"+start+" count:"+count+" after:"+after); // Log.e("demo", "beforeTextChanged start:"+start+" count:"+count+" after:"+after);
} }
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s)) { if (TextUtils.isEmpty(s)) {
return; return;
} }
String content = s.toString(); String content = s.toString();
// Log.e("demo", "content:"+content); // Log.e("demo", "content:"+content);
if (isNumeric(content)) { if (isNumeric(content)) {
int num = Integer.parseInt(content); int num = Integer.parseInt(content);
if (num > maxValue || num < minValue) { if (num > maxValue || num < minValue) {
s.delete(editStart, editStart+editCount); s.delete(editStart, editStart + editCount);
mEditTextPreference.getEditText().setText(s); mEditTextPreference.getEditText().setText(s);
Toast.makeText(mContext, "超出有效值范围", Toast.LENGTH_SHORT).show(); Toast.makeText(mContext, "超出有效值范围", Toast.LENGTH_SHORT).show();
} }
}else { } else {
s.delete(editStart, editStart+editCount); s.delete(editStart, editStart + editCount);
mEditTextPreference.getEditText().setText(s); mEditTextPreference.getEditText().setText(s);
Toast.makeText(mContext, "只能输入数字哦", Toast.LENGTH_SHORT).show(); Toast.makeText(mContext, "只能输入数字哦", Toast.LENGTH_SHORT).show();
} }
} }
/** /**
* 正则表达式-判断是否为数字 * 正则表达式-判断是否为数字
*/ */
public static boolean isNumeric(String str){ public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*"); Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches(); return pattern.matcher(str).matches();
} }
}; };

View File

@ -1,57 +1,55 @@
package com.iflytek.speech.util; package com.iflytek.speech.util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/** /**
* Xml结果解析类 * Xml结果解析类
*/ */
public class XmlParser { public class XmlParser {
public static String parseNluResult(String xml) public static String parseNluResult(String xml) {
{ StringBuffer buffer = new StringBuffer();
StringBuffer buffer = new StringBuffer(); try {
try // DOM builder
{ DocumentBuilder domBuilder = null;
// DOM builder // DOM doc
DocumentBuilder domBuilder = null; Document domDoc = null;
// DOM doc
Document domDoc = null;
// init DOM // init DOM
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
domBuilder = domFact.newDocumentBuilder(); domBuilder = domFact.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes()); InputStream is = new ByteArrayInputStream(xml.getBytes());
domDoc = domBuilder.parse(is); domDoc = domBuilder.parse(is);
// 获取根节点 // 获取根节点
Element root = (Element) domDoc.getDocumentElement(); Element root = (Element) domDoc.getDocumentElement();
Element raw = (Element)root.getElementsByTagName("rawtext").item(0); Element raw = (Element) root.getElementsByTagName("rawtext").item(0);
buffer.append("【识别结果】" + raw.getFirstChild().getNodeValue()); buffer.append("【识别结果】" + raw.getFirstChild().getNodeValue());
buffer.append("\n"); buffer.append("\n");
Element e = (Element)root.getElementsByTagName("result").item(0); Element e = (Element) root.getElementsByTagName("result").item(0);
Element focus = (Element)e.getElementsByTagName("focus").item(0); Element focus = (Element) e.getElementsByTagName("focus").item(0);
buffer.append("【FOCUS】" + focus.getFirstChild().getNodeValue()); buffer.append("【FOCUS】" + focus.getFirstChild().getNodeValue());
buffer.append("\n"); buffer.append("\n");
Element action = (Element)e.getElementsByTagName("action").item(0); Element action = (Element) e.getElementsByTagName("action").item(0);
Element operation = (Element)action.getElementsByTagName("operation").item(0); Element operation = (Element) action.getElementsByTagName("operation").item(0);
buffer.append("【ACTION】" + operation.getFirstChild().getNodeValue()); buffer.append("【ACTION】" + operation.getFirstChild().getNodeValue());
buffer.append("\n"); buffer.append("\n");
} catch (Exception e) {
e.printStackTrace();
}
buffer.append("【ALL】" + xml);
}catch(Exception e){ return buffer.toString();
e.printStackTrace(); }
};
buffer.append("【ALL】" + xml);
return buffer.toString();
}
} }

View File

@ -5,21 +5,17 @@ import android.app.Activity;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.Editor;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.view.Window; import android.view.Window;
import android.widget.EditText; import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast; import android.widget.Toast;
import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.GrammarListener; import com.iflytek.cloud.GrammarListener;
import com.iflytek.cloud.InitListener; import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.LexiconListener;
import com.iflytek.cloud.RecognizerListener; import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechConstant;
@ -27,285 +23,251 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.speech.util.FucUtil; import com.iflytek.speech.util.FucUtil;
import com.iflytek.speech.util.JsonParser; import com.iflytek.speech.util.JsonParser;
/*import com.iflytek.sunflower.FlowerCollector;*/
/** /**
* 识别示例 * 识别示例
*/ */
public class AsrDemo extends Activity implements OnClickListener{ public class AsrDemo extends Activity implements OnClickListener {
private static String TAG = AsrDemo.class.getSimpleName(); private static String TAG = AsrDemo.class.getSimpleName();
// 语音识别对象 // 语音识别对象
private SpeechRecognizer mAsr; private SpeechRecognizer mAsr;
private Toast mToast; private Toast mToast;
// 缓存 // 缓存
private SharedPreferences mSharedPreferences; private SharedPreferences mSharedPreferences;
// 云端语法文件 // 云端语法文件
private String mCloudGrammar = null; private String mCloudGrammar = null;
private static final String KEY_GRAMMAR_ABNF_ID = "grammar_abnf_id"; private static final String KEY_GRAMMAR_ABNF_ID = "grammar_abnf_id";
private static final String GRAMMAR_TYPE_ABNF = "abnf"; private static final String GRAMMAR_TYPE_ABNF = "abnf";
private static final String GRAMMAR_TYPE_BNF = "bnf"; private static final String GRAMMAR_TYPE_BNF = "bnf";
private String mEngineType = SpeechConstant.TYPE_CLOUD; private String mEngineType = SpeechConstant.TYPE_CLOUD;
@SuppressLint("ShowToast") @SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isrdemo); setContentView(R.layout.isrdemo);
initLayout(); initLayout();
// 初始化识别对象 // 初始化识别对象
mAsr = SpeechRecognizer.createRecognizer(AsrDemo.this, mInitListener); mAsr = SpeechRecognizer.createRecognizer(AsrDemo.this, mInitListener);
mCloudGrammar = FucUtil.readFile(this,"grammar_sample.abnf","utf-8"); mCloudGrammar = FucUtil.readFile(this, "grammar_sample.abnf", "utf-8");
mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE); mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT); }
} /**
* 初始化Layout
*/
private void initLayout() {
findViewById(R.id.isr_recognize).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_grammar).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_stop).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_cancel).setOnClickListener(AsrDemo.this);
/** }
* 初始化Layout
*/
private void initLayout() {
findViewById(R.id.isr_recognize).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_grammar).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_stop).setOnClickListener(AsrDemo.this);
findViewById(R.id.isr_cancel).setOnClickListener(AsrDemo.this);
} // 语法词典临时变量
private String mContent;
// 语法词典临时变量 // 函数调用返回值
String mContent; private int ret = 0;
// 函数调用返回值
int ret = 0;
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if( null == mAsr ){ if (null == mAsr) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688 // 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" ); this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return; return;
} }
if(null == mEngineType) { if (null == mEngineType) {
showTip("请先选择识别引擎类型"); showTip("请先选择识别引擎类型");
return; return;
} }
switch(view.getId()) switch (view.getId()) {
{ case R.id.isr_grammar:
case R.id.isr_grammar: showTip("上传预设关键词/语法文件");
showTip("上传预设关键词/语法文件"); // 在线-构建语法文件生成语法id
// 在线-构建语法文件生成语法id ((EditText) findViewById(R.id.isr_text)).setText(mCloudGrammar);
((EditText)findViewById(R.id.isr_text)).setText(mCloudGrammar); mContent = new String(mCloudGrammar);
mContent = new String(mCloudGrammar); //指定引擎类型
//指定引擎类型 mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType); mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
mAsr.setParameter(SpeechConstant.TEXT_ENCODING,"utf-8"); ret = mAsr.buildGrammar(GRAMMAR_TYPE_ABNF, mContent, mCloudGrammarListener);
ret = mAsr.buildGrammar(GRAMMAR_TYPE_ABNF, mContent, mCloudGrammarListener); if (ret != ErrorCode.SUCCESS) {
if(ret != ErrorCode.SUCCESS) showTip("语法构建失败,错误码:" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
showTip("语法构建失败,错误码:" + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); }
break;
// 开始识别
case R.id.isr_recognize:
((EditText) findViewById(R.id.isr_text)).setText(null);// 清空显示内容
// 设置参数
if (!setParam()) {
showTip("请先构建语法。");
return;
}
ret = mAsr.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码: " + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
break;
// 停止识别
case R.id.isr_stop:
mAsr.stopListening();
showTip("停止识别");
break;
// 取消识别
case R.id.isr_cancel:
mAsr.cancel();
showTip("取消识别");
break;
}
}
break; /**
// 开始识别
case R.id.isr_recognize:
((EditText)findViewById(R.id.isr_text)).setText(null);// 清空显示内容
// 设置参数
if (!setParam()) {
showTip("请先构建语法。");
return;
};
ret = mAsr.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码: " + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
break;
// 停止识别
case R.id.isr_stop:
mAsr.stopListening();
showTip("停止识别");
break;
// 取消识别
case R.id.isr_cancel:
mAsr.cancel();
showTip("取消识别");
break;
}
}
/**
* 初始化监听器 * 初始化监听器
*/ */
private InitListener mInitListener = new InitListener() { private InitListener mInitListener = new InitListener() {
@Override @Override
public void onInit(int code) { public void onInit(int code) {
Log.d(TAG, "SpeechRecognizer init() code = " + code); Log.d(TAG, "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) { if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:"+code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); showTip("初始化失败,错误码:" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} }
} }
}; };
/** /**
* 更新词典监听器
*/
private LexiconListener mLexiconListener = new LexiconListener() {
@Override
public void onLexiconUpdated(String lexiconId, SpeechError error) {
if(error == null){
showTip("词典更新成功");
}else{
showTip("词典更新失败,错误码:"+error.getErrorCode()+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
/**
* 云端构建语法监听器 * 云端构建语法监听器
*/ */
private GrammarListener mCloudGrammarListener = new GrammarListener() { private GrammarListener mCloudGrammarListener = new GrammarListener() {
@Override @Override
public void onBuildFinish(String grammarId, SpeechError error) { public void onBuildFinish(String grammarId, SpeechError error) {
if(error == null){ if (error == null) {
String grammarID = new String(grammarId); String grammarID = new String(grammarId);
Editor editor = mSharedPreferences.edit(); Editor editor = mSharedPreferences.edit();
if(!TextUtils.isEmpty(grammarId)) if (!TextUtils.isEmpty(grammarId))
editor.putString(KEY_GRAMMAR_ABNF_ID, grammarID); editor.putString(KEY_GRAMMAR_ABNF_ID, grammarID);
editor.commit(); editor.commit();
showTip("语法构建成功:" + grammarId); showTip("语法构建成功:" + grammarId);
}else{ } else {
showTip("语法构建失败,错误码:" + error.getErrorCode()+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); showTip("语法构建失败,错误码:" + error.getErrorCode() + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} }
} }
}; };
/** /**
* 识别监听器 * 识别监听器
*/ */
private RecognizerListener mRecognizerListener = new RecognizerListener() { private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override @Override
public void onVolumeChanged(int volume, byte[] data) { public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume); showTip("当前正在说话,音量大小:" + volume);
Log.d(TAG, "返回音频数据:"+data.length); Log.d(TAG, "返回音频数据:" + data.length);
} }
@Override @Override
public void onResult(final RecognizerResult result, boolean isLast) { public void onResult(final RecognizerResult result, boolean isLast) {
if (null != result) { if (null != result) {
Log.d(TAG, "recognizer result" + result.getResultString()); Log.d(TAG, "recognizer result" + result.getResultString());
String text ; String text;
if("cloud".equalsIgnoreCase(mEngineType)){ if ("cloud".equalsIgnoreCase(mEngineType)) {
text = JsonParser.parseGrammarResult(result.getResultString()); text = JsonParser.parseGrammarResult(result.getResultString());
}else { } else {
text = JsonParser.parseLocalGrammarResult(result.getResultString()); text = JsonParser.parseLocalGrammarResult(result.getResultString());
} }
// 显示 // 显示
((EditText)findViewById(R.id.isr_text)).setText(text); ((EditText) findViewById(R.id.isr_text)).setText(text);
} else { } else {
Log.d(TAG, "recognizer result : null"); Log.d(TAG, "recognizer result : null");
} }
} }
@Override @Override
public void onEndOfSpeech() { public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入 // 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话"); showTip("结束说话");
} }
@Override @Override
public void onBeginOfSpeech() { public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入 // 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话"); showTip("开始说话");
} }
@Override @Override
public void onError(SpeechError error) { public void onError(SpeechError error) {
showTip("onError Code" + error.getErrorCode()); showTip("onError Code" + error.getErrorCode());
} }
@Override @Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因 // 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
// 若使用本地能力会话id为null // 若使用本地能力会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) { // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid); // Log.d(TAG, "session id =" + sid);
// } // }
} }
}; };
private void showTip(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
mToast.show();
}
});
}
private void showTip(final String str) { /**
runOnUiThread(new Runnable() { * 参数设置
@Override *
public void run() { * @return
mToast.setText(str); */
mToast.show(); public boolean setParam() {
} boolean result = false;
}); //设置识别引擎
} mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
//设置返回结果为json格式
mAsr.setParameter(SpeechConstant.RESULT_TYPE, "json");
/** if ("cloud".equalsIgnoreCase(mEngineType)) {
* 参数设置 String grammarId = mSharedPreferences.getString(KEY_GRAMMAR_ABNF_ID, null);
* @return if (TextUtils.isEmpty(grammarId)) {
*/ result = false;
public boolean setParam(){ } else {
boolean result = false; //设置云端识别使用的语法id
//设置识别引擎 mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType); result = true;
//设置返回结果为json格式 }
mAsr.setParameter(SpeechConstant.RESULT_TYPE, "json"); }
// 设置音频保存路径保存音频格式支持pcmwav
mAsr.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/asr.wav");
return result;
}
if("cloud".equalsIgnoreCase(mEngineType)) @Override
{ protected void onDestroy() {
String grammarId = mSharedPreferences.getString(KEY_GRAMMAR_ABNF_ID, null); super.onDestroy();
if(TextUtils.isEmpty(grammarId))
{
result = false;
}else {
//设置云端识别使用的语法id
mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
result = true;
}
}
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 if (null != mAsr) {
mAsr.setParameter(SpeechConstant.AUDIO_FORMAT,"wav"); // 退出时释放连接
mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/asr.wav"); mAsr.cancel();
return result; mAsr.destroy();
} }
}
@Override
protected void onDestroy() {
super.onDestroy();
if( null != mAsr ){
// 退出时释放连接
mAsr.cancel();
mAsr.destroy();
}
}
@Override
protected void onResume() {
//移动数据统计分析
/* FlowerCollector.onResume(AsrDemo.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
@Override
protected void onPause() {
//移动数据统计分析
/*FlowerCollector.onPageEnd(TAG);
FlowerCollector.onPause(AsrDemo.this);*/
super.onPause();
}
} }

View File

@ -1,12 +1,5 @@
package com.iflytek.voicedemo; package com.iflytek.voicedemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
@ -14,10 +7,6 @@ import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
@ -36,489 +25,404 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog; import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener; import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.cloud.util.ContactManager;
import com.iflytek.cloud.util.ContactManager.ContactListener;
import com.iflytek.speech.setting.IatSettings; import com.iflytek.speech.setting.IatSettings;
import com.iflytek.speech.util.FucUtil; import com.iflytek.speech.util.FucUtil;
import com.iflytek.speech.util.JsonParser; import com.iflytek.speech.util.JsonParser;
/*import com.iflytek.sunflower.FlowerCollector;*/
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class IatDemo extends Activity implements OnClickListener { public class IatDemo extends Activity implements OnClickListener {
private static String TAG = IatDemo.class.getSimpleName(); private static String TAG = IatDemo.class.getSimpleName();
// 语音听写对象 // 语音听写对象
private SpeechRecognizer mIat; private SpeechRecognizer mIat;
// 语音听写UI // 语音听写UI
private RecognizerDialog mIatDialog; private RecognizerDialog mIatDialog;
// 用HashMap存储听写结果 // 用HashMap存储听写结果
private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>(); private HashMap<String, String> mIatResults = new LinkedHashMap<>();
private EditText mResultText; private EditText mResultText;
private EditText showContacts; private EditText showContacts;
private TextView languageText; private TextView languageText;
private Toast mToast; private Toast mToast;
private SharedPreferences mSharedPreferences; private SharedPreferences mSharedPreferences;
// 引擎类型 // 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD; private String mEngineType = SpeechConstant.TYPE_CLOUD;
private String[] languageEntries ; private String[] languageEntries;
private String[] languageValues; private String[] languageValues;
private String language="zh_cn"; private String language = "zh_cn";
private int selectedNum=0; private int selectedNum = 0;
private String resultType = "json"; private String resultType = "json";
private boolean cyclic = false;//音频流识别是否循环调用 private StringBuffer buffer = new StringBuffer();
private StringBuffer buffer = new StringBuffer();
Handler han = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x001) {
executeStream();
}
}
};
private static int flg=0;
@SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.iatdemo);
languageEntries = getResources().getStringArray(R.array.iat_language_entries);
languageValues = getResources().getStringArray(R.array.iat_language_value);
initLayout();
// 初始化识别无UI识别对象
// 使用SpeechRecognizer对象可根据回调消息自定义界面
mIat = SpeechRecognizer.createRecognizer(IatDemo.this, mInitListener);
// 初始化听写Dialog如果只使用有UI听写功能无需创建SpeechRecognizer
// 使用UI听写功能请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
mIatDialog = new RecognizerDialog(IatDemo.this, mInitListener);
mSharedPreferences = getSharedPreferences(IatSettings.PREFER_NAME,
Activity.MODE_PRIVATE);
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
mResultText = ((EditText) findViewById(R.id.iat_text));
showContacts = (EditText) findViewById(R.id.iat_contacts);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.iatdemo);
languageEntries = getResources().getStringArray(R.array.iat_language_entries);
languageValues = getResources().getStringArray(R.array.iat_language_value);
initLayout();
// 初始化识别无UI识别对象
// 使用SpeechRecognizer对象可根据回调消息自定义界面
mIat = SpeechRecognizer.createRecognizer(IatDemo.this, mInitListener);
// 初始化听写Dialog如果只使用有UI听写功能无需创建SpeechRecognizer
// 使用UI听写功能请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
mIatDialog = new RecognizerDialog(IatDemo.this, mInitListener);
mSharedPreferences = getSharedPreferences(IatSettings.PREFER_NAME,
Activity.MODE_PRIVATE);
mResultText = ((EditText) findViewById(R.id.iat_text));
showContacts = (EditText) findViewById(R.id.iat_contacts);
}
/** /**
* 初始化Layout * 初始化Layout
*/ */
private void initLayout() { private void initLayout() {
findViewById(R.id.iat_recognize).setOnClickListener(IatDemo.this); findViewById(R.id.iat_recognize).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_recognize_stream).setOnClickListener(IatDemo.this); findViewById(R.id.iat_recognize_stream).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_upload_contacts).setOnClickListener(IatDemo.this); findViewById(R.id.iat_upload_userwords).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_upload_userwords).setOnClickListener(IatDemo.this); findViewById(R.id.iat_stop).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_stop).setOnClickListener(IatDemo.this); findViewById(R.id.iat_cancel).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_cancel).setOnClickListener(IatDemo.this); findViewById(R.id.image_iat_set).setOnClickListener(IatDemo.this);
findViewById(R.id.image_iat_set).setOnClickListener(IatDemo.this); findViewById(R.id.languageText).setOnClickListener(IatDemo.this);
findViewById(R.id.languageText).setOnClickListener(IatDemo.this); }
}
int ret = 0; // 函数调用返回值 int ret = 0; // 函数调用返回值
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if( null == mIat ){ if (null == mIat) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688 // 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" ); this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return; return;
} }
switch (view.getId()) { switch (view.getId()) {
// 进入参数设置页面 // 进入参数设置页面
case R.id.image_iat_set: case R.id.image_iat_set:
Intent intents = new Intent(IatDemo.this, IatSettings.class); Intent intents = new Intent(IatDemo.this, IatSettings.class);
startActivity(intents); startActivity(intents);
break; break;
// 开始听写 // 开始听写
// 如何判断一次听写结束OnResult isLast=true 或者 onError // 如何判断一次听写结束OnResult isLast=true 或者 onError
case R.id.iat_recognize: case R.id.iat_recognize:
// 移动数据分析收集开始听写事件 buffer.setLength(0);
// FlowerCollector.onEvent(IatDemo.this, "iat_recognize"); mResultText.setText(null);// 清空显示内容
mIatResults.clear();
// 设置参数
setParam();
boolean isShowDialog = mSharedPreferences.getBoolean(
getString(R.string.pref_key_iat_show), true);
if (isShowDialog) {
// 显示听写对话框
mIatDialog.setListener(mRecognizerDialogListener);
mIatDialog.show();
showTip(getString(R.string.text_begin));
} else {
// 不显示听写对话框
ret = mIat.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("听写失败,错误码:" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} else {
showTip(getString(R.string.text_begin));
}
}
break;
// 音频流识别
case R.id.iat_recognize_stream:
executeStream();
break;
case R.id.languageText:
setLanguage(view);
break;
// 停止听写
case R.id.iat_stop:
mIat.stopListening();
showTip("停止听写");
break;
// 取消听写
case R.id.iat_cancel:
mIat.cancel();
showTip("取消听写");
break;
// 上传用户词表
case R.id.iat_upload_userwords:
String contents = FucUtil.readFile(IatDemo.this, "userwords", "utf-8");
showContacts.setText(contents);
// 指定引擎类型
mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
mIat.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
ret = mIat.updateLexicon("userword", contents, mLexiconListener);
if (ret != ErrorCode.SUCCESS)
showTip("上传热词失败,错误码:" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
break;
default:
break;
}
}
buffer.setLength(0); /**
mResultText.setText(null);// 清空显示内容 * 初始化监听器
mIatResults.clear(); */
// 设置参数 private InitListener mInitListener = new InitListener() {
setParam();
boolean isShowDialog = mSharedPreferences.getBoolean(
getString(R.string.pref_key_iat_show), true);
if (isShowDialog) {
// 显示听写对话框
mIatDialog.setListener(mRecognizerDialogListener);
mIatDialog.show();
showTip(getString(R.string.text_begin));
} else {
// 不显示听写对话框
ret = mIat.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("听写失败,错误码:" + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} else {
showTip(getString(R.string.text_begin));
}
}
break;
// 音频流识别
case R.id.iat_recognize_stream:
executeStream();
break;
case R.id.languageText:
setLanguage(view);
break;
// 停止听写
case R.id.iat_stop:
mIat.stopListening();
showTip("停止听写");
break;
// 取消听写
case R.id.iat_cancel:
mIat.cancel();
showTip("取消听写");
break;
// 上传联系人
case R.id.iat_upload_contacts:
showTip(getString(R.string.text_upload_contacts));
ContactManager mgr = ContactManager.createManager(IatDemo.this,
mContactListener);
mgr.asyncQueryAllContactsName();
break;
// 上传用户词表
case R.id.iat_upload_userwords:
showTip(getString(R.string.text_upload_userwords));
String contents = FucUtil.readFile(IatDemo.this, "userwords","utf-8");
showContacts.setText(contents);
// 指定引擎类型 @Override
mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); public void onInit(int code) {
mIat.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8"); Log.d(TAG, "SpeechRecognizer init() code = " + code);
ret = mIat.updateLexicon("userword", contents, mLexiconListener); if (code != ErrorCode.SUCCESS) {
if (ret != ErrorCode.SUCCESS) showTip("初始化失败,错误码:" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
showTip("上传热词失败,错误码:" + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); }
break; }
default: };
break;
}
}
/** /**
* 初始化监听器 * 在线听写支持多种小语种设置支持语言类型如下
*/ * <item>zh_cn</item> 中文
private InitListener mInitListener = new InitListener() { * <item>en_us</item> 英文
* <item>ja_jp</item> 日语
* <item>ru-ru</item> 俄语
* <item>es_es</item> 西班牙语
* <item>fr_fr</item> 法语
* <item>ko_kr</item> 韩语
*
* @param v
*/
private void setLanguage(View v) {
new AlertDialog.Builder(v.getContext()).setTitle("语种语言种类")
.setSingleChoiceItems(languageEntries, // 单选框有几项,各是什么名字
0, // 默认的选项
new DialogInterface.OnClickListener() { // 点击单选框后的处理
public void onClick(DialogInterface dialog,
int which) { // 点击了哪一项
language = languageValues[which];
((TextView) findViewById(R.id.languageText)).setText("你选择的是:" + languageEntries[which]);
selectedNum = which;
dialog.dismiss();
}
}).show();
mIat.setParameter(SpeechConstant.LANGUAGE, language);
}
@Override /**
public void onInit(int code) { * 上传联系人/词表监听器
Log.d(TAG, "SpeechRecognizer init() code = " + code); */
if (code != ErrorCode.SUCCESS) { private LexiconListener mLexiconListener = new LexiconListener() {
showTip("初始化失败,错误码:" + code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
/** @Override
* 在线听写支持多种小语种设置支持语言类型如下 public void onLexiconUpdated(String lexiconId, SpeechError error) {
* <item>zh_cn</item> 中文 if (error != null) {
* <item>en_us</item> 英文 showTip(error.toString());
* <item>ja_jp</item> 日语 } else {
* <item>ru-ru</item> 俄语 showTip(getString(R.string.text_upload_success));
* <item>es_es</item> 西班牙语 }
* <item>fr_fr</item> 法语 }
* <item>ko_kr</item> 韩语 };
* @param v
*/
private void setLanguage(View v){
new AlertDialog.Builder(v.getContext()).setTitle("语种语言种类")
.setSingleChoiceItems(languageEntries, // 单选框有几项,各是什么名字
0, // 默认的选项
new DialogInterface.OnClickListener() { // 点击单选框后的处理
public void onClick(DialogInterface dialog,
int which) { // 点击了哪一项
language = languageValues[which];
((TextView)findViewById(R.id.languageText)).setText("你选择的是:"+languageEntries[which]);
selectedNum = which;
dialog.dismiss();
}
}).show();
mIat.setParameter(SpeechConstant.LANGUAGE, language);
}
/** /**
* 上传联系人/词表监听器 * 听写监听器
*/ */
private LexiconListener mLexiconListener = new LexiconListener() { private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override @Override
public void onLexiconUpdated(String lexiconId, SpeechError error) { public void onBeginOfSpeech() {
if (error != null) { // 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip(error.toString()); showTip("开始说话");
} else { }
showTip(getString(R.string.text_upload_success));
}
}
};
/**
* 听写监听器
*/
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// Tips
// 错误码10118(您没有说话)可能是录音机权限被禁需要提示用户打开应用的录音权限
@Override
public void onError(SpeechError error) {
// Tips
// 错误码10118(您没有说话)可能是录音机权限被禁需要提示用户打开应用的录音权限
Log.d(TAG, "onError " + error.getPlainDescription(true));
showTip(error.getPlainDescription(true)); showTip(error.getPlainDescription(true));
} }
@Override @Override
public void onEndOfSpeech() { public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入 // 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话"); showTip("结束说话");
} }
@Override @Override
public void onResult(RecognizerResult results, boolean isLast) { public void onResult(RecognizerResult results, boolean isLast) {
Log.d(TAG, results.getResultString()); Log.d(TAG, results.getResultString());
System.out.println(flg++); if (isLast) {
if (resultType.equals("json")) { Log.d(TAG, "onResult 结束");
}
if (resultType.equals("json")) {
printResult(results);
return;
}
if (resultType.equals("plain")) {
buffer.append(results.getResultString());
mResultText.setText(buffer.toString());
mResultText.setSelection(mResultText.length());
}
}
printResult(results); @Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小 = " + volume + " 返回音频数据 = " + data.length);
}
}else if(resultType.equals("plain")) { @Override
buffer.append(results.getResultString()); public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
mResultText.setText(buffer.toString()); // 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
mResultText.setSelection(mResultText.length()); // 若使用本地能力会话id为null
} // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
if (isLast & cyclic) { /**
// TODO 最后的结果 * 显示结果
Message message = Message.obtain(); */
message.what = 0x001; private void printResult(RecognizerResult results) {
han.sendMessageDelayed(message,100); String text = JsonParser.parseIatResult(results.getResultString());
} String sn = null;
} // 读取json结果中的sn字段
try {
JSONObject resultJson = new JSONObject(results.getResultString());
sn = resultJson.optString("sn");
} catch (JSONException e) {
e.printStackTrace();
}
@Override mIatResults.put(sn, text);
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
Log.d(TAG, "返回音频数据:"+data.length);
}
@Override StringBuffer resultBuffer = new StringBuffer();
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { for (String key : mIatResults.keySet()) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因 resultBuffer.append(mIatResults.get(key));
// 若使用本地能力会话id为null }
// if (SpeechEvent.EVENT_SESSION_ID == eventType) { mResultText.setText(resultBuffer.toString());
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); mResultText.setSelection(mResultText.length());
// Log.d(TAG, "session id =" + sid); }
// }
}
};
private void printResult(RecognizerResult results) { /**
String text = JsonParser.parseIatResult(results.getResultString()); * 听写UI监听器
*/
private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
// 返回结果
public void onResult(RecognizerResult results, boolean isLast) {
printResult(results);
}
String sn = null; // 识别回调错误
// 读取json结果中的sn字段 public void onError(SpeechError error) {
try { showTip(error.getPlainDescription(true));
JSONObject resultJson = new JSONObject(results.getResultString()); }
sn = resultJson.optString("sn");
} catch (JSONException e) {
e.printStackTrace();
}
mIatResults.put(sn, text); };
StringBuffer resultBuffer = new StringBuffer();
for (String key : mIatResults.keySet()) {
resultBuffer.append(mIatResults.get(key));
}
mResultText.setText(resultBuffer.toString());
mResultText.setSelection(mResultText.length());
}
/**
* 听写UI监听器
*/
private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
public void onResult(RecognizerResult results, boolean isLast) {
printResult(results);
}
/**
* 识别回调错误.
*/
public void onError(SpeechError error) {
showTip(error.getPlainDescription(true));
}
};
/**
* 获取联系人监听器
*/
private ContactListener mContactListener = new ContactListener() {
@Override
public void onContactQueryFinish(final String contactInfos, boolean changeFlag) {
// 实际应用中除第一次上传之外之后应该通过changeFlag判断是否需要上传否则会造成不必要的流量.
// 每当联系人发生变化该接口都将会被回调可通过ContactManager.destroy()销毁对象解除回调
// if(changeFlag) {
// 指定引擎类型
runOnUiThread(new Runnable() {
public void run() {
showContacts.setText(contactInfos);
}
});
mIat.setParameter(SpeechConstant.ENGINE_TYPE,SpeechConstant.TYPE_CLOUD);
mIat.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
ret = mIat.updateLexicon("contact", contactInfos, mLexiconListener);
if (ret != ErrorCode.SUCCESS) {
showTip("上传联系人失败:" + ret);
}
}
};
private void showTip(final String str) {
mToast.setText(str);
mToast.show();
}
/**
* 参数设置
*
* @return
*/
public void setParam() {
// 清空参数
mIat.setParameter(SpeechConstant.PARAMS, null);
// 设置听写引擎
mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
// 设置返回结果格式
mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);
if(language.equals("zh_cn")) { private void showTip(final String str) {
String lag = mSharedPreferences.getString("iat_language_preference", if (mToast != null) {
"mandarin"); mToast.cancel();
Log.e(TAG,"language:"+language);// 设置语言 }
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
// 设置语言区域 mToast.show();
mIat.setParameter(SpeechConstant.ACCENT, lag); }
}else {
mIat.setParameter(SpeechConstant.LANGUAGE, language); /**
} * 参数设置
Log.e(TAG,"last language:"+mIat.getParameter(SpeechConstant.LANGUAGE)); *
* @return
*/
public void setParam() {
// 清空参数
mIat.setParameter(SpeechConstant.PARAMS, null);
// 设置听写引擎
mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
// 设置返回结果格式
mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);
//此处用于设置dialog中不显示错误码信息 if (language.equals("zh_cn")) {
//mIat.setParameter("view_tips_plain","false"); String lag = mSharedPreferences.getString("iat_language_preference",
"mandarin");
// 设置语言
Log.e(TAG, "language = " + language);
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
// 设置语言区域
mIat.setParameter(SpeechConstant.ACCENT, lag);
} else {
mIat.setParameter(SpeechConstant.LANGUAGE, language);
}
Log.e(TAG, "last language:" + mIat.getParameter(SpeechConstant.LANGUAGE));
// 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理 //此处用于设置dialog中不显示错误码信息
mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000")); //mIat.setParameter("view_tips_plain","false");
// 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音 // 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000")); mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点 // 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音
mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1")); mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav"); mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
}
// 设置音频保存路径保存音频格式支持pcmwav.
mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/iat.wav");
}
@Override /**
protected void onDestroy() { * 执行音频流识别操作
super.onDestroy(); */
private void executeStream() {
buffer.setLength(0);
mResultText.setText(null);// 清空显示内容
mIatResults.clear();
// 设置参数
setParam();
// 设置音频来源为外部文件
mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
// 也可以像以下这样直接设置音频文件路径识别要求设置文件在sdcard上的全路径
// mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-2");
// mIat.setParameter(SpeechConstant.ASR_SOURCE_PATH, "sdcard/XXX/XXX.pcm");
ret = mIat.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码:" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
return;
}
try {
InputStream open = getAssets().open("iattest.wav");
byte[] buff = new byte[1280];
while (open.available() > 0) {
int read = open.read(buff);
mIat.writeAudio(buff, 0, read);
}
mIat.stopListening();
} catch (IOException e) {
mIat.cancel();
showTip("读取音频流失败");
}
}
if( null != mIat ){ @Override
// 退出时释放连接 protected void onDestroy() {
mIat.cancel(); super.onDestroy();
mIat.destroy(); if (mIat != null) {
} // 退出时释放连接
} mIat.cancel();
mIat.destroy();
@Override }
protected void onResume() { }
// 开放统计 移动数据统计分析
/*FlowerCollector.onResume(IatDemo.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
@Override
protected void onPause() {
// 开放统计 移动数据统计分析
super.onPause();
}
//执行音频流识别操作
private void executeStream() {
buffer.setLength(0);
mResultText.setText(null);// 清空显示内容
mIatResults.clear();
// 设置参数
setParam();
// 设置音频来源为外部文件
mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
// 也可以像以下这样直接设置音频文件路径识别要求设置文件在sdcard上的全路径
// mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-2");
//mIat.setParameter(SpeechConstant.ASR_SOURCE_PATH, "sdcard/XXX/XXX.pcm");
ret = mIat.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码:" + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} else {
byte[] audioData = FucUtil.readAudioFile(IatDemo.this, "iattest.wav");
if (null != audioData) {
showTip(getString(R.string.text_begin_recognizer));
// 一次也可以分多次写入音频文件数据数据格式必须是采样率为8KHz或16KHz本地识别只支持16K采样率云端都支持
// 位长16bit单声道的wav或者pcm
// 写入8KHz采样的音频时必须先调用setParameter(SpeechConstant.SAMPLE_RATE, "8000")设置正确的采样率
// 当音频过长静音部分时长超过VAD_EOS将导致静音后面部分不能识别
ArrayList<byte[]> bytes = FucUtil.splitBuffer(audioData,audioData.length,audioData.length/3);
for(int i=0;i<bytes.size();i++) {
mIat.writeAudio(bytes.get(i), 0, bytes.get(i).length );
try {
Thread.sleep(1000);
}catch(Exception e){
}
}
mIat.stopListening();
/*mIat.writeAudio(audioData, 0, audioData.length );
mIat.stopListening();*/
} else {
mIat.cancel();
showTip("读取音频流失败");
}
}
}
} }

View File

@ -14,7 +14,6 @@ import android.media.ExifInterface;
import android.media.MediaScannerConnection; import android.media.MediaScannerConnection;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Log; import android.util.Log;
import android.view.Gravity; import android.view.Gravity;
@ -32,9 +31,7 @@ import com.iflytek.cloud.IdentityVerifier;
import com.iflytek.cloud.InitListener; import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechError;
import com.iflytek.speech.util.FaceUtil;
import com.iflytek.voicedemo.R; import com.iflytek.voicedemo.R;
import com.iflytek.voicedemo.faceonline.OnlineFaceDemo;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -51,420 +48,417 @@ import java.io.IOException;
* @author hjyu * @author hjyu
* @date 2017/9/28. * @date 2017/9/28.
* @see <a href="http://www.xfyun.cn">讯飞开放平台</a> * @see <a href="http://www.xfyun.cn">讯飞开放平台</a>
* */ */
public class FaceIdentifyActivity extends Activity implements OnClickListener { public class FaceIdentifyActivity extends Activity implements OnClickListener {
private final static String TAG = FaceIdentifyActivity.class.getSimpleName(); private final static String TAG = FaceIdentifyActivity.class.getSimpleName();
// 用户输入的组ID // 用户输入的组ID
private String mGroupId; private String mGroupId;
// 身份鉴别对象 // 身份鉴别对象
private IdentityVerifier mIdVerifier; private IdentityVerifier mIdVerifier;
private TextView txt_groupid; private TextView txt_groupid;
private ProgressDialog mProDialog; private ProgressDialog mProDialog;
private Toast mToast; private Toast mToast;
// 选择图片后返回 // 选择图片后返回
public static final int REQUEST_PICTURE_CHOOSE = 1; public static final int REQUEST_PICTURE_CHOOSE = 1;
// 拍照后返回 // 拍照后返回
private final static int REQUEST_CAMERA_IMAGE = 2; private final static int REQUEST_CAMERA_IMAGE = 2;
// 裁剪图片成功后返回 // 裁剪图片成功后返回
public static final int REQUEST_INTENT_CROP = 3; public static final int REQUEST_INTENT_CROP = 3;
private Bitmap mImageBitmap = null; private Bitmap mImageBitmap = null;
private byte[] mImageData = null; private byte[] mImageData = null;
private File mPictureFile; private File mPictureFile;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_face_identify); setContentView(R.layout.activity_face_identify);
// 身份验证对象初始化 // 身份验证对象初始化
mGroupId = getIntent().getStringExtra("group_id"); mGroupId = getIntent().getStringExtra("group_id");
// 对象初始化监听器 // 对象初始化监听器
mIdVerifier = IdentityVerifier.createVerifier(FaceIdentifyActivity.this, new InitListener() { mIdVerifier = IdentityVerifier.createVerifier(FaceIdentifyActivity.this, new InitListener() {
@Override @Override
public void onInit(int errorCode) { public void onInit(int errorCode) {
if (ErrorCode.SUCCESS == errorCode) { if (ErrorCode.SUCCESS == errorCode) {
showTip("引擎初始化成功"); showTip("引擎初始化成功");
} else { } else {
showTip("引擎初始化失败,错误码:" + errorCode+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); showTip("引擎初始化失败,错误码:" + errorCode + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} }
} }
}); });
// 初始化界面 // 初始化界面
initUI(); initUI();
} }
private void initUI() { private void initUI() {
findViewById(R.id.online_pick).setOnClickListener(FaceIdentifyActivity.this); findViewById(R.id.online_pick).setOnClickListener(FaceIdentifyActivity.this);
findViewById(R.id.online_camera).setOnClickListener(FaceIdentifyActivity.this); findViewById(R.id.online_camera).setOnClickListener(FaceIdentifyActivity.this);
findViewById(R.id.btn_identity).setOnClickListener(FaceIdentifyActivity.this); findViewById(R.id.btn_identity).setOnClickListener(FaceIdentifyActivity.this);
txt_groupid = (TextView)findViewById(R.id.txt_groupid); txt_groupid = (TextView) findViewById(R.id.txt_groupid);
mProDialog = new ProgressDialog(FaceIdentifyActivity.this); mProDialog = new ProgressDialog(FaceIdentifyActivity.this);
mProDialog.setCancelable(true); mProDialog.setCancelable(true);
mProDialog.setTitle("请稍候"); mProDialog.setTitle("请稍候");
// cancel进度框时取消正在进行的操作 // cancel进度框时取消正在进行的操作
mProDialog.setOnCancelListener(new OnCancelListener() { mProDialog.setOnCancelListener(new OnCancelListener() {
@Override @Override
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
if (null != mIdVerifier) { if (null != mIdVerifier) {
mIdVerifier.cancel(); mIdVerifier.cancel();
} }
} }
}); });
mToast = Toast.makeText(FaceIdentifyActivity.this, "", Toast.LENGTH_SHORT); mToast = Toast.makeText(FaceIdentifyActivity.this, "", Toast.LENGTH_SHORT);
mToast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); mToast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
txt_groupid.setText(mGroupId); txt_groupid.setText(mGroupId);
} }
/** /**
* 人脸鉴别监听器 * 人脸鉴别监听器
*/ */
private IdentityListener mSearchListener = new IdentityListener() { private IdentityListener mSearchListener = new IdentityListener() {
@Override @Override
public void onResult(IdentityResult result, boolean islast) { public void onResult(IdentityResult result, boolean islast) {
Log.d(TAG, result.getResultString()); Log.d(TAG, result.getResultString());
dismissProDialog(); dismissProDialog();
handleResult(result); handleResult(result);
} }
@Override @Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
} }
@Override @Override
public void onError(SpeechError error) { public void onError(SpeechError error) {
dismissProDialog(); dismissProDialog();
showTip(error.getPlainDescription(true)); showTip(error.getPlainDescription(true));
} }
}; };
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if( null == mIdVerifier ){ if (null == mIdVerifier) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688 // 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" ); showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return; return;
} }
switch (view.getId()) { switch (view.getId()) {
case R.id.online_pick: case R.id.online_pick:
// 调用系统相册完成选图 // 调用系统相册完成选图
Intent intent = new Intent(); Intent intent = new Intent();
intent.setType("image/*"); intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK); intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICTURE_CHOOSE); startActivityForResult(intent, REQUEST_PICTURE_CHOOSE);
break; break;
case R.id.online_camera: case R.id.online_camera:
// 设置相机拍照后照片保存路径 // 设置相机拍照后照片保存路径
mPictureFile = new File(Environment.getExternalStorageDirectory(), mPictureFile = new File(getExternalFilesDir("msc").getAbsolutePath(),
"picture" + System.currentTimeMillis()/1000 + ".jpg"); "picture" + System.currentTimeMillis() / 1000 + ".jpg");
// 启动拍照,并保存到临时文件 // 启动拍照,并保存到临时文件
Intent mIntent = new Intent(); Intent mIntent = new Intent();
mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile)); mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile));
mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
startActivityForResult(mIntent, REQUEST_CAMERA_IMAGE); startActivityForResult(mIntent, REQUEST_CAMERA_IMAGE);
break; break;
case R.id.btn_identity: case R.id.btn_identity:
if (null != mImageData) { if (null != mImageData) {
mProDialog.setMessage("鉴别中..."); mProDialog.setMessage("鉴别中...");
mProDialog.show(); mProDialog.show();
// 清空参数 // 清空参数
mIdVerifier.setParameter(SpeechConstant.PARAMS, null); mIdVerifier.setParameter(SpeechConstant.PARAMS, null);
// 设置业务场景 // 设置业务场景
mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ifr"); mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ifr");
// 设置业务类型 // 设置业务类型
mIdVerifier.setParameter(SpeechConstant.MFV_SST, "identify"); mIdVerifier.setParameter(SpeechConstant.MFV_SST, "identify");
// 设置监听器开始会话 // 设置监听器开始会话
mIdVerifier.startWorking(mSearchListener); mIdVerifier.startWorking(mSearchListener);
// 子业务执行参数若无可以传空字符传 // 子业务执行参数若无可以传空字符传
StringBuffer params = new StringBuffer(); StringBuffer params = new StringBuffer();
params.append(",group_id=" + mGroupId +",topc=3"); params.append(",group_id=" + mGroupId + ",topc=3");
// 向子业务写入数据人脸数据可以一次写入 // 向子业务写入数据人脸数据可以一次写入
mIdVerifier.writeData("ifr", params.toString(), mImageData, 0, mImageData.length); mIdVerifier.writeData("ifr", params.toString(), mImageData, 0, mImageData.length);
// 写入完毕 // 写入完毕
mIdVerifier.stopWrite("ifr"); mIdVerifier.stopWrite("ifr");
} else { } else {
showTip("请选择图片后再鉴别"); showTip("请选择图片后再鉴别");
} }
break; break;
default: default:
break; break;
} }
} }
protected void handleResult(IdentityResult result) { protected void handleResult(IdentityResult result) {
if (null == result) { if (null == result) {
return; return;
} }
try { try {
String resultStr = result.getResultString(); String resultStr = result.getResultString();
JSONObject resultJson = new JSONObject(resultStr); JSONObject resultJson = new JSONObject(resultStr);
if(ErrorCode.SUCCESS == resultJson.getInt("ret")) if (ErrorCode.SUCCESS == resultJson.getInt("ret")) {
{ // 跳转到结果展示页面
// 跳转到结果展示页面 Intent intent = new Intent(FaceIdentifyActivity.this, ResultIdentifyActivity.class);
Intent intent = new Intent(FaceIdentifyActivity.this, ResultIdentifyActivity.class); intent.putExtra("result", resultStr);
intent.putExtra("result", resultStr); startActivity(intent);
startActivity(intent); this.finish();
this.finish(); } else {
} showTip("鉴别失败!");
else { }
showTip("鉴别失败!"); } catch (JSONException e) {
} e.printStackTrace();
} catch (JSONException e) { }
e.printStackTrace(); }
}
}
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { if (resultCode != RESULT_OK) {
return; return;
} }
String fileSrc = null; String fileSrc = null;
if (requestCode == REQUEST_PICTURE_CHOOSE ) { if (requestCode == REQUEST_PICTURE_CHOOSE) {
if ("file".equals(data.getData().getScheme())) { if ("file".equals(data.getData().getScheme())) {
// 有些低版本机型返回的Uri模式为file // 有些低版本机型返回的Uri模式为file
fileSrc = data.getData().getPath(); fileSrc = data.getData().getPath();
} else { } else {
// Uri模型为content // Uri模型为content
String[] proj = {MediaStore.Images.Media.DATA}; String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(data.getData(), proj, Cursor cursor = getContentResolver().query(data.getData(), proj,
null, null, null); null, null, null);
cursor.moveToFirst(); cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileSrc = cursor.getString(idx); fileSrc = cursor.getString(idx);
cursor.close(); cursor.close();
} }
// 跳转到图片裁剪页面 // 跳转到图片裁剪页面
cropPicture(this,Uri.fromFile(new File(fileSrc))); cropPicture(this, Uri.fromFile(new File(fileSrc)));
} else if (requestCode == REQUEST_CAMERA_IMAGE) { } else if (requestCode == REQUEST_CAMERA_IMAGE) {
if (null == mPictureFile) { if (null == mPictureFile) {
showTip("拍照失败,请重试"); showTip("拍照失败,请重试");
return; return;
} }
fileSrc = mPictureFile.getAbsolutePath(); fileSrc = mPictureFile.getAbsolutePath();
updateGallery(fileSrc); updateGallery(fileSrc);
// 跳转到图片裁剪页面 // 跳转到图片裁剪页面
cropPicture(this,Uri.fromFile(new File(fileSrc))); cropPicture(this, Uri.fromFile(new File(fileSrc)));
} else if (requestCode == REQUEST_INTENT_CROP) { } else if (requestCode == REQUEST_INTENT_CROP) {
// 获取返回数据 // 获取返回数据
Bitmap bmp = data.getParcelableExtra("data"); Bitmap bmp = data.getParcelableExtra("data");
// 获取裁剪后图片保存路径 // 获取裁剪后图片保存路径
fileSrc = getImagePath(); fileSrc = getImagePath();
// 若返回数据不为null保存至本地防止裁剪时未能正常保存 // 若返回数据不为null保存至本地防止裁剪时未能正常保存
if(null != bmp){ if (null != bmp) {
saveBitmapToFile(bmp); saveBitmapToFile(bmp);
} }
// 获取图片的宽和高 // 获取图片的宽和高
Options options = new Options(); Options options = new Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
mImageBitmap = BitmapFactory.decodeFile(fileSrc, options); mImageBitmap = BitmapFactory.decodeFile(fileSrc, options);
// 压缩图片 // 压缩图片
options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max( options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
(double) options.outWidth / 1024f, (double) options.outWidth / 1024f,
(double) options.outHeight / 1024f))); (double) options.outHeight / 1024f)));
options.inJustDecodeBounds = false; options.inJustDecodeBounds = false;
mImageBitmap = BitmapFactory.decodeFile(fileSrc, options); mImageBitmap = BitmapFactory.decodeFile(fileSrc, options);
// 若mImageBitmap为空则图片信息不能正常获取 // 若mImageBitmap为空则图片信息不能正常获取
if(null == mImageBitmap) { if (null == mImageBitmap) {
showTip("图片信息无法正常获取!"); showTip("图片信息无法正常获取!");
return; return;
} }
// 部分手机会对图片做旋转这里检测旋转角度 // 部分手机会对图片做旋转这里检测旋转角度
int degree = readPictureDegree(fileSrc); int degree = readPictureDegree(fileSrc);
if (degree != 0) { if (degree != 0) {
// 把图片旋转为正的方向 // 把图片旋转为正的方向
mImageBitmap = rotateImage(degree, mImageBitmap); mImageBitmap = rotateImage(degree, mImageBitmap);
} }
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
//可根据流量及网络状况对图片进行压缩 //可根据流量及网络状况对图片进行压缩
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos); mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
mImageData = baos.toByteArray(); mImageData = baos.toByteArray();
((ImageView) findViewById(R.id.online_img)).setImageBitmap(mImageBitmap); ((ImageView) findViewById(R.id.online_img)).setImageBitmap(mImageBitmap);
} }
} }
@Override @Override
public void finish() { public void finish() {
if (null != mProDialog) { if (null != mProDialog) {
mProDialog.dismiss(); mProDialog.dismiss();
} }
setResult(RESULT_OK); setResult(RESULT_OK);
super.finish(); super.finish();
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
if (null != mIdVerifier) { if (null != mIdVerifier) {
mIdVerifier.destroy(); mIdVerifier.destroy();
mIdVerifier = null; mIdVerifier = null;
} }
} }
/** /**
* 读取图片属性旋转的角度 * 读取图片属性旋转的角度
* *
* @param path 图片绝对路径 * @param path 图片绝对路径
* @return degree 旋转的角度 * @return degree 旋转的角度
*/ */
public static int readPictureDegree(String path) { public static int readPictureDegree(String path) {
int degree = 0; int degree = 0;
try { try {
ExifInterface exifInterface = new ExifInterface(path); ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt( int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL); ExifInterface.ORIENTATION_NORMAL);
switch (orientation) { switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90; degree = 90;
break; break;
case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180; degree = 180;
break; break;
case ExifInterface.ORIENTATION_ROTATE_270: case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270; degree = 270;
break; break;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return degree; return degree;
} }
private void updateGallery(String filename) { private void updateGallery(String filename) {
MediaScannerConnection.scanFile(this, new String[] {filename}, null, MediaScannerConnection.scanFile(this, new String[]{filename}, null,
new MediaScannerConnection.OnScanCompletedListener() { new MediaScannerConnection.OnScanCompletedListener() {
@Override @Override
public void onScanCompleted(String path, Uri uri) { public void onScanCompleted(String path, Uri uri) {
} }
}); });
} }
/** /**
* 旋转图片 * 旋转图片
* *
* @param angle * @param angle
* @param bitmap * @param bitmap
* @return Bitmap * @return Bitmap
*/ */
public static Bitmap rotateImage(int angle, Bitmap bitmap) { public static Bitmap rotateImage(int angle, Bitmap bitmap) {
// 图片旋转矩阵 // 图片旋转矩阵
Matrix matrix = new Matrix(); Matrix matrix = new Matrix();
matrix.postRotate(angle); matrix.postRotate(angle);
// 得到旋转后的图片 // 得到旋转后的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true); bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap; return resizedBitmap;
} }
/** /**
* Toast弹出提示 * Toast弹出提示
* @param str *
*/ * @param str
private void showTip(final String str) { */
mToast.setText(str); private void showTip(final String str) {
mToast.show(); mToast.setText(str);
} mToast.show();
}
/*** /***
* 裁剪图片 * 裁剪图片
* @param activity Activity * @param activity Activity
* @param uri 图片的Uri * @param uri 图片的Uri
*/ */
public void cropPicture(Activity activity, Uri uri) { public void cropPicture(Activity activity, Uri uri) {
Intent innerIntent = new Intent("com.android.camera.action.CROP"); Intent innerIntent = new Intent("com.android.camera.action.CROP");
innerIntent.setDataAndType(uri, "image/*"); innerIntent.setDataAndType(uri, "image/*");
innerIntent.putExtra("crop", "true");// 才能出剪辑的小方框不然没有剪辑功能只能选取图片 innerIntent.putExtra("crop", "true");// 才能出剪辑的小方框不然没有剪辑功能只能选取图片
innerIntent.putExtra("aspectX", 1); // 放大缩小比例的X innerIntent.putExtra("aspectX", 1); // 放大缩小比例的X
innerIntent.putExtra("aspectY", 1);// 放大缩小比例的X 这里的比例为 1:1 innerIntent.putExtra("aspectY", 1);// 放大缩小比例的X 这里的比例为 1:1
innerIntent.putExtra("outputX", 320); //这个是限制输出图片大小 innerIntent.putExtra("outputX", 320); //这个是限制输出图片大小
innerIntent.putExtra("outputY", 320); innerIntent.putExtra("outputY", 320);
innerIntent.putExtra("return-data", true); innerIntent.putExtra("return-data", true);
// 切图大小不足输出无黑框 // 切图大小不足输出无黑框
innerIntent.putExtra("scale", true); innerIntent.putExtra("scale", true);
innerIntent.putExtra("scaleUpIfNeeded", true); innerIntent.putExtra("scaleUpIfNeeded", true);
innerIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getImagePath()))); innerIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getImagePath())));
innerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); innerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
activity.startActivityForResult(innerIntent, REQUEST_INTENT_CROP); activity.startActivityForResult(innerIntent, REQUEST_INTENT_CROP);
} }
/** /**
* 设置保存图片路径 * 设置保存图片路径
* @return *
*/ * @return
private String getImagePath(){ */
String path; private String getImagePath() {
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = getExternalFilesDir("msc_face").getAbsolutePath() + "/MFVDemo";
return null; File folder = new File(path);
} if (!folder.exists()) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/MFVDemo/"; folder.mkdirs();
File folder = new File(path); }
if (folder != null && !folder.exists()) { path += "/mfvtest.jpg";
folder.mkdirs(); return path;
} }
path += "mfvtest.jpg";
return path;
}
/** /**
* 保存Bitmap至本地 * 保存Bitmap至本地
* @param bmp *
*/ * @param bmp
private void saveBitmapToFile(Bitmap bmp){ */
String file_path = getImagePath(); private void saveBitmapToFile(Bitmap bmp) {
File file = new File(file_path); String file_path = getImagePath();
FileOutputStream fOut; File file = new File(file_path);
try { FileOutputStream fOut;
fOut = new FileOutputStream(file); try {
bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut = new FileOutputStream(file);
fOut.flush(); bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.close(); fOut.flush();
} catch (FileNotFoundException e) { fOut.close();
e.printStackTrace(); } catch (FileNotFoundException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
} }
}
private void dismissProDialog() { private void dismissProDialog() {
if (null != mProDialog) { if (null != mProDialog) {
mProDialog.dismiss(); mProDialog.dismiss();
} }
} }
} }

View File

@ -41,215 +41,211 @@ import java.util.Map;
/** /**
* 声纹密码和人脸识别相关组操作 * 声纹密码和人脸识别相关组操作
* 支持组创建/添加成员/查询组成员/删除成员/删除组/ * 支持组创建/添加成员/查询组成员/删除成员/删除组/
*
* @author hjyu
* @date 2017/9/28.
* @see this#createGroup() * @see this#createGroup()
* @see this#joinGroup(String) * @see this#joinGroup(String)
* @see //this#queryGroups() * @see //this#queryGroups()
* @see this#deleteGroup(String, boolean) ,第二个参数用于标示删除组成员or组 * @see this#deleteGroup(String, boolean) ,第二个参数用于标示删除组成员or组
*
* @author hjyu
* @date 2017/9/28.
* @see <a href="http://www.xfyun.cn">讯飞开放平台</a> * @see <a href="http://www.xfyun.cn">讯飞开放平台</a>
*/ */
public class GroupManagerActivity extends Activity implements OnClickListener ,AdapterView.OnItemClickListener { public class GroupManagerActivity extends Activity implements OnClickListener, AdapterView.OnItemClickListener {
private final static String TAG = GroupManagerActivity.class.getSimpleName(); private final static String TAG = GroupManagerActivity.class.getSimpleName();
// 身份验证对象 // 身份验证对象
private IdentityVerifier mIdVerifier; private IdentityVerifier mIdVerifier;
// 用户名信息 // 用户名信息
private TextView mUserNameText; private TextView mUserNameText;
EditText etGroupId; EditText etGroupId;
EditText etGroupName; EditText etGroupName;
private Toast mToast; private Toast mToast;
MyAdapter adapter; MyAdapter adapter;
private ProgressDialog mProDialog; private ProgressDialog mProDialog;
String authId; String authId;
String mfv_type; String mfv_type;
ArrayList<Map<String,String>> mList; ArrayList<Map<String, String>> mList;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_group_manager); setContentView(R.layout.activity_group_manager);
mIdVerifier = IdentityVerifier.createVerifier(this, null); mIdVerifier = IdentityVerifier.createVerifier(this, null);
authId = getIntent().getStringExtra("auth_id"); authId = getIntent().getStringExtra("auth_id");
mfv_type = getIntent().getStringExtra("mfv_scenes"); mfv_type = getIntent().getStringExtra("mfv_scenes");
mList = new ArrayList<Map<String, String>>(); mList = new ArrayList<Map<String, String>>();
// 画面初期化 // 画面初期化
initLayout(); initLayout();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
} }
/** /**
* 画面初期化 * 画面初期化
*/ */
@SuppressLint("ShowToast") @SuppressLint("ShowToast")
private void initLayout() { private void initLayout() {
mProDialog = new ProgressDialog(this); mProDialog = new ProgressDialog(this);
// 等待框设置为不可取消 // 等待框设置为不可取消
mProDialog.setCancelable(true); mProDialog.setCancelable(true);
mProDialog.setCanceledOnTouchOutside(false); mProDialog.setCanceledOnTouchOutside(false);
mProDialog.setTitle("请稍候"); mProDialog.setTitle("请稍候");
mProDialog.setOnCancelListener(new OnCancelListener() { mProDialog.setOnCancelListener(new OnCancelListener() {
@Override @Override
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
// cancel进度框时,取消正在进行的操作 // cancel进度框时,取消正在进行的操作
if (null != mIdVerifier) { if (null != mIdVerifier) {
mIdVerifier.cancel(); mIdVerifier.cancel();
} }
} }
}); });
LayoutInflater inflater = LayoutInflater.from(this); LayoutInflater inflater = LayoutInflater.from(this);
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.group_header_layout, null); RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.group_header_layout, null);
mUserNameText = (TextView) view.findViewById(R.id.txt_username); mUserNameText = (TextView) view.findViewById(R.id.txt_username);
mUserNameText.setText(authId); mUserNameText.setText(authId);
stopProgress(); stopProgress();
// 创建组 // 创建组
((Button) view.findViewById(R.id.btn_group_create)).setOnClickListener(this); ((Button) view.findViewById(R.id.btn_group_create)).setOnClickListener(this);
// 加入组 // 加入组
((Button) view.findViewById(R.id.btn_group_join)).setOnClickListener(this); ((Button) view.findViewById(R.id.btn_group_join)).setOnClickListener(this);
((Button) view.findViewById(R.id.btn_person_delete)).setOnClickListener(this); ((Button) view.findViewById(R.id.btn_person_delete)).setOnClickListener(this);
((Button) view.findViewById(R.id.btn_group_delete)).setOnClickListener(this); ((Button) view.findViewById(R.id.btn_group_delete)).setOnClickListener(this);
// 输入组id // 输入组id
etGroupId = ((EditText) view.findViewById(R.id.edt_group_id)); etGroupId = ((EditText) view.findViewById(R.id.edt_group_id));
// 输入组名称 // 输入组名称
etGroupName = ((EditText) view.findViewById(R.id.edt_group_name)); etGroupName = ((EditText) view.findViewById(R.id.edt_group_name));
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
// 绑定XML中的ListView作为Item的容器 // 绑定XML中的ListView作为Item的容器
ListView list = (ListView) findViewById(R.id.lv_my_group); ListView list = (ListView) findViewById(R.id.lv_my_group);
list.setOnItemClickListener(this); list.setOnItemClickListener(this);
list.addHeaderView(view); list.addHeaderView(view);
// 去除行与行之间的黑线 // 去除行与行之间的黑线
list.setDivider(null); list.setDivider(null);
// 添加并且显示 // 添加并且显示
adapter = new MyAdapter(this, mList ); adapter = new MyAdapter(this, mList);
list.setAdapter(adapter); list.setAdapter(adapter);
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if( null == mIdVerifier ){ if (null == mIdVerifier) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688 // 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" ); showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return; return;
} }
switch (v.getId()) { switch (v.getId()) {
case R.id.btn_group_create: case R.id.btn_group_create:
createGroup(); createGroup();
break; break;
case R.id.btn_group_join: case R.id.btn_group_join:
joinGroup(null); joinGroup(null);
break; break;
case R.id.btn_person_delete: case R.id.btn_person_delete:
deleteGroup(null, false); deleteGroup(null, false);
break; break;
case R.id.btn_group_delete: case R.id.btn_group_delete:
deleteGroup(null, true); deleteGroup(null, true);
break; break;
default: default:
break; break;
} }
} }
@Override @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent init = new Intent(); Intent init = new Intent();
Map<String,String> map = (Map<String,String>)parent.getAdapter().getItem(position); Map<String, String> map = (Map<String, String>) parent.getAdapter().getItem(position);
init.putExtra("group_id",map.get("group_id")); init.putExtra("group_id", map.get("group_id"));
if (mfv_type.equals("ivp")) { init.setClass(GroupManagerActivity.this, FaceIdentifyActivity.class);
init.setClass(GroupManagerActivity.this,VocalIdentifyActivity.class); startActivity(init);
}else { }
init.setClass(GroupManagerActivity.this,FaceIdentifyActivity.class);
}
startActivity(init);
}
/** /**
* 开启进度条 * 开启进度条
*/ */
private void startProgress(String msg) { private void startProgress(String msg) {
mProDialog.setMessage(msg); mProDialog.setMessage(msg);
mProDialog.show(); mProDialog.show();
((RelativeLayout) findViewById(R.id.group_manager_layout)).setEnabled(false); ((RelativeLayout) findViewById(R.id.group_manager_layout)).setEnabled(false);
} }
/** /**
* 关闭进度条 * 关闭进度条
*/ */
private void stopProgress() { private void stopProgress() {
if (null != mProDialog) { if (null != mProDialog) {
mProDialog.dismiss(); mProDialog.dismiss();
} }
((RelativeLayout) findViewById(R.id.group_manager_layout)).setEnabled(true); ((RelativeLayout) findViewById(R.id.group_manager_layout)).setEnabled(true);
} }
private void createGroup() { private void createGroup() {
String groupName = etGroupName.getText().toString(); String groupName = etGroupName.getText().toString();
if (TextUtils.isEmpty(groupName)) { if (TextUtils.isEmpty(groupName)) {
showTip("请填写groupName"); showTip("请填写groupName");
return; return;
} }
startProgress("正在创建组..."); startProgress("正在创建组...");
// sst=addscope=groupgroup_name=famil; // sst=addscope=groupgroup_name=famil;
// 设置人脸模型操作参数 // 设置人脸模型操作参数
// 清空参数 // 清空参数
mIdVerifier.setParameter(SpeechConstant.PARAMS, null); mIdVerifier.setParameter(SpeechConstant.PARAMS, null);
// 设置会话场景 // 设置会话场景
mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt"); mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt");
// 用户id // 用户id
mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId); mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId);
// 设置模型参数若无可以传空字符传 // 设置模型参数若无可以传空字符传
StringBuffer params = new StringBuffer(); StringBuffer params = new StringBuffer();
params.append("auth_id=" + authId); params.append("auth_id=" + authId);
params.append(",scope=group"); params.append(",scope=group");
params.append(",group_name=" + groupName); params.append(",group_name=" + groupName);
// 执行模型操作 // 执行模型操作
mIdVerifier.execute("ipt", "add", params.toString(), mCreateListener); mIdVerifier.execute("ipt", "add", params.toString(), mCreateListener);
} }
private void joinGroup(String groupIdCreate) { private void joinGroup(String groupIdCreate) {
String groupId; String groupId;
if (!TextUtils.isEmpty(groupIdCreate)) { if (!TextUtils.isEmpty(groupIdCreate)) {
groupId = groupIdCreate; groupId = groupIdCreate;
} else { } else {
groupId = etGroupId.getText().toString(); groupId = etGroupId.getText().toString();
} }
if (TextUtils.isEmpty(groupId)) { if (TextUtils.isEmpty(groupId)) {
showTip("请填写groupId"); showTip("请填写groupId");
return; return;
} }
startProgress("正在加入组..."); startProgress("正在加入组...");
// sst=addauth_id=eqhegroup_id=123456scope=person // sst=addauth_id=eqhegroup_id=123456scope=person
mIdVerifier.setParameter(SpeechConstant.PARAMS, null); mIdVerifier.setParameter(SpeechConstant.PARAMS, null);
// 设置会话场景 // 设置会话场景
mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt"); mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt");
// 用户id // 用户id
mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId); mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId);
// 设置模型参数若无可以传空字符传 // 设置模型参数若无可以传空字符传
StringBuffer params2 = new StringBuffer(); StringBuffer params2 = new StringBuffer();
params2.append("auth_id=" + authId); params2.append("auth_id=" + authId);
params2.append(",scope=person"); params2.append(",scope=person");
params2.append(",group_id=" + groupId); params2.append(",group_id=" + groupId);
// 执行模型操作 // 执行模型操作
mIdVerifier.execute("ipt", "add", params2.toString(), mAddListener); mIdVerifier.execute("ipt", "add", params2.toString(), mAddListener);
} }
// /** // /**
// * 查询指定组中成员 // * 查询指定组中成员
@ -300,237 +296,239 @@ public class GroupManagerActivity extends Activity implements OnClickListener ,A
mIdVerifier.execute("ipt", "query", params2.toString(), mQueryListener); mIdVerifier.execute("ipt", "query", params2.toString(), mQueryListener);
}*/ }*/
private void deleteGroup(String groupJoin, boolean deleteGroup) { private void deleteGroup(String groupJoin, boolean deleteGroup) {
String groupId; String groupId;
if (!TextUtils.isEmpty(groupJoin)) { if (!TextUtils.isEmpty(groupJoin)) {
groupId = groupJoin; groupId = groupJoin;
} else { } else {
groupId = etGroupId.getText().toString(); groupId = etGroupId.getText().toString();
} }
if (TextUtils.isEmpty(groupId)) { if (TextUtils.isEmpty(groupId)) {
showTip("请填写groupId"); showTip("请填写groupId");
return; return;
} }
startProgress("正在删除..."); startProgress("正在删除...");
// sst=addauth_id=eqhegroup_id=123456scope=person // sst=addauth_id=eqhegroup_id=123456scope=person
mIdVerifier.setParameter(SpeechConstant.PARAMS, null); mIdVerifier.setParameter(SpeechConstant.PARAMS, null);
// 设置会话场景 // 设置会话场景
mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt"); mIdVerifier.setParameter(SpeechConstant.MFV_SCENES, "ipt");
// 用户id // 用户id
mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId); mIdVerifier.setParameter(SpeechConstant.AUTH_ID, authId);
// 设置模型参数若无可以传空字符传 // 设置模型参数若无可以传空字符传
StringBuffer params2 = new StringBuffer(); StringBuffer params2 = new StringBuffer();
if(deleteGroup) { if (deleteGroup) {
params2.append("scope=group"); params2.append("scope=group");
} else { } else {
// 删除组中指定auth_id用户 // 删除组中指定auth_id用户
params2.append("scope=person"); params2.append("scope=person");
params2.append(",auth_id="+authId); params2.append(",auth_id=" + authId);
} }
params2.append(",group_id=" + groupId); params2.append(",group_id=" + groupId);
// 执行模型操作 // 执行模型操作
mIdVerifier.execute("ipt", "delete", params2.toString(), mDeleteListener); mIdVerifier.execute("ipt", "delete", params2.toString(), mDeleteListener);
} }
/** /**
* 创建组监听器 * 创建组监听器
*/ */
private IdentityListener mCreateListener = new IdentityListener() { private IdentityListener mCreateListener = new IdentityListener() {
@Override @Override
public void onResult(IdentityResult result, boolean islast) { public void onResult(IdentityResult result, boolean islast) {
stopProgress(); stopProgress();
Log.d(TAG, result.getResultString()); Log.d(TAG, result.getResultString());
try { try {
JSONObject resObj = new JSONObject(result.getResultString()); JSONObject resObj = new JSONObject(result.getResultString());
resObj.getString("group_id"); resObj.getString("group_id");
// 创建成功后将自己加入到组里 // 创建成功后将自己加入到组里
joinGroup(resObj.getString("group_id")); joinGroup(resObj.getString("group_id"));
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
showTip("组创建成功"); showTip("组创建成功");
} }
@Override @Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
} }
@Override @Override
public void onError(SpeechError error) { public void onError(SpeechError error) {
stopProgress(); stopProgress();
showTip(error.getPlainDescription(true)); showTip(error.getPlainDescription(true));
} }
}; };
/** /**
* 加入组监听器 * 加入组监听器
*/ */
private IdentityListener mAddListener = new IdentityListener() { private IdentityListener mAddListener = new IdentityListener() {
@Override @Override
public void onResult(IdentityResult result, boolean islast) { public void onResult(IdentityResult result, boolean islast) {
Log.d(TAG, result.getResultString()); Log.d(TAG, result.getResultString());
try { try {
JSONObject resObj = new JSONObject(result.getResultString()); JSONObject resObj = new JSONObject(result.getResultString());
// 保存到用户信息中用来显示用户加人的组 // 保存到用户信息中用来显示用户加人的组
Map<String,String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("group_name",resObj.getString("group_name")); map.put("group_name", resObj.getString("group_name"));
map.put("group_id",resObj.getString("group_id")); map.put("group_id", resObj.getString("group_id"));
synchronized (mList) { synchronized (mList) {
if (mList != null && mList.size() >0) { if (mList != null && mList.size() > 0) {
for(int i = 0;i<mList.size();i++) { for (int i = 0; i < mList.size(); i++) {
if(!mList.contains(map)) { if (!mList.contains(map)) {
mList.add(map); mList.add(map);
} }
} }
}else { } else {
mList.add(map); mList.add(map);
} }
mList.notify(); mList.notify();
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
showTip("加入组成功"); showTip("加入组成功");
//adapter.setArray(mList); //adapter.setArray(mList);
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
stopProgress(); stopProgress();
} }
@Override @Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
} }
@Override @Override
public void onError(SpeechError error) { public void onError(SpeechError error) {
stopProgress(); stopProgress();
showTip(error.getPlainDescription(true)); showTip(error.getPlainDescription(true));
} }
}; };
private IdentityListener mQueryListener = new IdentityListener() { private IdentityListener mQueryListener = new IdentityListener() {
@Override @Override
public void onResult(IdentityResult result, boolean islast) { public void onResult(IdentityResult result, boolean islast) {
Log.d(TAG, result.getResultString()); Log.d(TAG, result.getResultString());
showTip("查询成功"); showTip("查询成功");
stopProgress(); stopProgress();
} }
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
} @Override
@Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
public void onError(SpeechError error) {
Log.d(TAG, error.getPlainDescription(true));
//showTip(ErrorDesc.getDesc(error) + ":" + error.getErrorCode());
stopProgress();
}
};
private IdentityListener mDeleteListener = new IdentityListener() { }
@Override
public void onResult(IdentityResult result, boolean islast) {
Log.d(TAG, result.getResultString());
try {
JSONObject resObj = new JSONObject(result.getResultString());
Log.d(TAG,"resObj == "+resObj.toString());
int ret = resObj.getInt("ret");
if(0 != ret) {
onError(new SpeechError(ret));
return;
} else {
if(result.getResultString().contains("user")) {
String user = resObj.getString("user");
showTip("删除组成员"+user+"成功");
} else {
showTip("删除组成功");
// 保存到用户信息中用来显示用户加人的组
for (Map<String,String> map1:mList){
if (map1.get("group_id").equals(resObj.getString("group_id"))){
mList.remove(map1);
}
}
} @Override
} public void onError(SpeechError error) {
} catch (JSONException e) { Log.d(TAG, error.getPlainDescription(true));
e.printStackTrace(); //showTip(ErrorDesc.getDesc(error) + ":" + error.getErrorCode());
} stopProgress();
adapter.setArray(mList); }
adapter.notifyDataSetChanged(); };
stopProgress();
}
@Override private IdentityListener mDeleteListener = new IdentityListener() {
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { @Override
public void onResult(IdentityResult result, boolean islast) {
Log.d(TAG, result.getResultString());
try {
JSONObject resObj = new JSONObject(result.getResultString());
Log.d(TAG, "resObj == " + resObj.toString());
int ret = resObj.getInt("ret");
if (0 != ret) {
onError(new SpeechError(ret));
return;
} else {
if (result.getResultString().contains("user")) {
String user = resObj.getString("user");
showTip("删除组成员" + user + "成功");
} else {
showTip("删除组成功");
// 保存到用户信息中用来显示用户加人的组
for (Map<String, String> map1 : mList) {
if (map1.get("group_id").equals(resObj.getString("group_id"))) {
mList.remove(map1);
}
}
} }
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.setArray(mList);
adapter.notifyDataSetChanged();
stopProgress();
}
@Override @Override
public void onError(SpeechError error) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
stopProgress();
showTip(error.getPlainDescription(true));
}
};
private void showTip(final String str) { }
mToast.setText(str);
mToast.show();
}
private class MyAdapter extends BaseAdapter { @Override
public void onError(SpeechError error) {
stopProgress();
showTip(error.getPlainDescription(true));
}
};
private Context context; private void showTip(final String str) {
private LayoutInflater inflater; mToast.setText(str);
public ArrayList<Map<String,String>> arr; mToast.show();
}
public MyAdapter(Context context, ArrayList<Map<String,String>> array) { private class MyAdapter extends BaseAdapter {
super();
this.context = context;
inflater = LayoutInflater.from(context);
arr = array;
}
@Override private Context context;
public int getCount() { private LayoutInflater inflater;
if (arr != null) public ArrayList<Map<String, String>> arr;
return arr.size();
else
return 0;
}
@Override public MyAdapter(Context context, ArrayList<Map<String, String>> array) {
public Object getItem(int arg0) { super();
if (arr.get(arg0) != null) { this.context = context;
return arr.get(arg0); inflater = LayoutInflater.from(context);
} arr = array;
return arg0; }
}
@Override @Override
public long getItemId(int arg0) { public int getCount() {
return arg0; if (arr != null)
} return arr.size();
else
return 0;
}
public void setArray(ArrayList<Map<String,String>> list) { @Override
this.arr = list; public Object getItem(int arg0) {
} if (arr.get(arg0) != null) {
return arr.get(arg0);
}
return arg0;
}
@Override @Override
public View getView(int position, View view, ViewGroup parent) { public long getItemId(int arg0) {
if (view == null) { return arg0;
view = inflater.inflate(R.layout.item_group, null); }
}
final TextView edit = (TextView) view.findViewById(R.id.group_item_content); public void setArray(ArrayList<Map<String, String>> list) {
Map<String,String> map2 = arr.get(arr.size() - position - 1); this.arr = list;
edit.setText(map2.get("group_id")+"("+map2.get("group_name")+")"); // 在重构adapter的时候不至于数据错乱 }
return view;
} @Override
} public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.item_group, null);
}
final TextView edit = (TextView) view.findViewById(R.id.group_item_content);
Map<String, String> map2 = arr.get(arr.size() - position - 1);
edit.setText(map2.get("group_id") + "(" + map2.get("group_name") + ")"); // 在重构adapter的时候不至于数据错乱
return view;
}
}
} }

View File

@ -22,31 +22,32 @@ import java.text.DecimalFormat;
/** /**
* 1:N检测结果解析界面 * 1:N检测结果解析界面
*
* @author hjyu * @author hjyu
* @date 2017/9/28. * @date 2017/9/28.
* @see <a href="http://www.xfyun.cn">讯飞开放平台</a> * @see <a href="http://www.xfyun.cn">讯飞开放平台</a>
*/ */
public class ResultIdentifyActivity extends Activity implements OnClickListener { public class ResultIdentifyActivity extends Activity implements OnClickListener {
private String result; private String result;
JSONArray candidates; JSONArray candidates;
MyAdapter adapter; MyAdapter adapter;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_result_identify); setContentView(R.layout.activity_result_identify);
initUI(); initUI();
} }
private void initUI() { private void initUI() {
TextView title = (TextView) findViewById(R.id.txt_idf_result_title); TextView title = (TextView) findViewById(R.id.txt_idf_result_title);
result = getIntent().getStringExtra("result"); result = getIntent().getStringExtra("result");
// 结果形式 // 结果形式
// result = " // result = "
/*{ /*{
"ret":0, "ret":0,
"group_id":"xxxxxx", "group_id":"xxxxxx",
@ -62,104 +63,104 @@ public class ResultIdentifyActivity extends Activity implements OnClickListener
"ssub":"ivp", "ssub":"ivp",
"topc":1 "topc":1
}*/ }*/
try { try {
JSONObject obj = new JSONObject(result); JSONObject obj = new JSONObject(result);
// 组名称 // 组名称
((TextView)findViewById(R.id.txt_group_name)).setText(obj.getString("group_name")); ((TextView) findViewById(R.id.txt_group_name)).setText(obj.getString("group_name"));
JSONObject ifv_result = obj.getJSONObject("ifv_result"); JSONObject ifv_result = obj.getJSONObject("ifv_result");
candidates = ifv_result.getJSONArray("candidates"); candidates = ifv_result.getJSONArray("candidates");
// 鉴别结果 // 鉴别结果
// 绑定XML中的ListView作为Item的容器 // 绑定XML中的ListView作为Item的容器
ListView list = (ListView) findViewById(R.id.lv_identify_result); ListView list = (ListView) findViewById(R.id.lv_identify_result);
// 去除行与行之间的黑线 // 去除行与行之间的黑线
list.setDivider(null); list.setDivider(null);
// 添加并且显示 // 添加并且显示
adapter = new MyAdapter(ResultIdentifyActivity.this, candidates); adapter = new MyAdapter(ResultIdentifyActivity.this, candidates);
list.setAdapter(adapter); list.setAdapter(adapter);
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// 相似度排行 // 相似度排行
private class MyAdapter extends BaseAdapter { private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater; private LayoutInflater inflater;
public JSONArray arr; public JSONArray arr;
public MyAdapter(Context context, JSONArray array) { public MyAdapter(Context context, JSONArray array) {
super(); super();
inflater = LayoutInflater.from(context); inflater = LayoutInflater.from(context);
arr = array; arr = array;
} }
@Override @Override
public int getCount() { public int getCount() {
if (arr != null) if (arr != null)
return arr.length(); return arr.length();
else else
return 0; return 0;
} }
@Override @Override
public Object getItem(int arg0) { public Object getItem(int arg0) {
return arg0; return arg0;
} }
@Override @Override
public long getItemId(int arg0) { public long getItemId(int arg0) {
return arg0; return arg0;
} }
@Override @Override
public View getView(int position, View view, ViewGroup parent) { public View getView(int position, View view, ViewGroup parent) {
if (view == null) { if (view == null) {
view = inflater.inflate(R.layout.item_identify_result, null); view = inflater.inflate(R.layout.item_identify_result, null);
} }
final TextView tx_number = (TextView) view.findViewById(R.id.identify_item_number); final TextView tx_number = (TextView) view.findViewById(R.id.identify_item_number);
final TextView tx_user = (TextView) view.findViewById(R.id.identify_item_user); final TextView tx_user = (TextView) view.findViewById(R.id.identify_item_user);
final TextView tx_score = (TextView) view.findViewById(R.id.identify_item_score); final TextView tx_score = (TextView) view.findViewById(R.id.identify_item_score);
JSONObject obj; JSONObject obj;
try { try {
obj = arr.getJSONObject(position); obj = arr.getJSONObject(position);
tx_number.setText("" + getChineseNumber(position + 1) + ":"); tx_number.setText("" + getChineseNumber(position + 1) + ":");
tx_user.setText(obj.optString("user")); tx_user.setText(obj.optString("user"));
DecimalFormat df = new DecimalFormat("0.00"); DecimalFormat df = new DecimalFormat("0.00");
Double score = obj.optDouble("score"); Double score = obj.optDouble("score");
String scoreStr = df.format(score) + "%"; String scoreStr = df.format(score) + "%";
tx_score.setText(scoreStr); tx_score.setText(scoreStr);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
return view; return view;
} }
} }
private String getChineseNumber(int number) { private String getChineseNumber(int number) {
String[] str = { "", "", "", "", "", "", "", "", "", "" }; String[] str = {"", "", "", "", "", "", "", "", "", ""};
String ss[] = new String[] { "", "", "", "", "", "", "", "", "亿" }; String ss[] = new String[]{"", "", "", "", "", "", "", "", "亿"};
String s = String.valueOf(number); String s = String.valueOf(number);
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
String index = String.valueOf(s.charAt(i)); String index = String.valueOf(s.charAt(i));
sb = sb.append(str[Integer.parseInt(index)]); sb = sb.append(str[Integer.parseInt(index)]);
} }
String sss = String.valueOf(sb); String sss = String.valueOf(sb);
int i = 0; int i = 0;
for (int j = sss.length(); j > 0; j--) { for (int j = sss.length(); j > 0; j--) {
sb = sb.insert(j, ss[i++]); sb = sb.insert(j, ss[i++]);
} }
return sb.toString(); return sb.toString();
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
} }
} }

View File

@ -1,169 +1,168 @@
package com.iflytek.voicedemo; package com.iflytek.voicedemo;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.ise.result.Result;
import com.iflytek.ise.result.xml.XmlResultParser;
import com.iflytek.speech.setting.IseSettings;
import com.iflytek.speech.util.FucUtil;
/*import com.iflytek.sunflower.FlowerCollector;*/
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Base64;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.view.Window; import android.view.Window;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.iflytek.ise.result.Result;
import com.iflytek.ise.result.xml.XmlResultParser;
import com.iflytek.speech.setting.IseSettings;
/** /**
* 语音评测demo * 语音评测demo
*/ */
public class IseDemo extends Activity implements OnClickListener { public class IseDemo extends Activity implements OnClickListener {
private static String TAG = IseDemo.class.getSimpleName(); private static String TAG = IseDemo.class.getSimpleName();
private final static String PREFER_NAME = "ise_settings"; private final static String PREFER_NAME = "ise_settings";
private final static int REQUEST_CODE_SETTINGS = 1; private final static int REQUEST_CODE_SETTINGS = 1;
private EditText mEvaTextEditText; private EditText mEvaTextEditText;
private EditText mResultEditText; private TextView mResultEditText;
private Button mIseStartButton; private Button mIseStartButton;
private Toast mToast; private Toast mToast;
// 评测语种 // 评测语种
private String language; private String language;
// 评测题型 // 评测题型
private String category; private String category;
// 结果等级 // 结果等级
private String result_level; private String result_level;
private String mLastResult; private String mLastResult;
private SpeechEvaluator mIse; private SpeechEvaluator mIse;
// 评测监听接口 // 评测监听接口
private EvaluatorListener mEvaluatorListener = new EvaluatorListener() { private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {
@Override @Override
public void onResult(EvaluatorResult result, boolean isLast) { public void onResult(EvaluatorResult result, boolean isLast) {
Log.d(TAG, "evaluator result :" + isLast); Log.d(TAG, "evaluator result :" + isLast);
if (isLast) { if (isLast) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(result.getResultString()); builder.append(result.getResultString());
if(!TextUtils.isEmpty(builder)) { if (!TextUtils.isEmpty(builder)) {
mResultEditText.setText(builder.toString()); mResultEditText.setText(builder.toString());
} }
mIseStartButton.setEnabled(true); mIseStartButton.setEnabled(true);
mLastResult = builder.toString(); mLastResult = builder.toString();
showTip("评测结束"); showTip("评测结束");
} }
} }
@Override @Override
public void onError(SpeechError error) { public void onError(SpeechError error) {
mIseStartButton.setEnabled(true); mIseStartButton.setEnabled(true);
if(error != null) { if (error != null) {
showTip("error:"+ error.getErrorCode() + "," + error.getErrorDescription()); showTip("error:" + error.getErrorCode() + "," + error.getErrorDescription());
mResultEditText.setText(""); mResultEditText.setText("");
mResultEditText.setHint("请点击“开始评测”按钮"); mResultEditText.setHint("请点击“开始评测”按钮");
} else { } else {
Log.d(TAG, "evaluator over"); Log.d(TAG, "evaluator over");
} }
} }
@Override @Override
public void onBeginOfSpeech() { public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入 // 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
Log.d(TAG, "evaluator begin"); Log.d(TAG, "evaluator begin");
} }
@Override @Override
public void onEndOfSpeech() { public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入 // 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
Log.d(TAG, "evaluator stoped"); Log.d(TAG, "evaluator stoped");
} }
@Override @Override
public void onVolumeChanged(int volume, byte[] data) { public void onVolumeChanged(int volume, byte[] data) {
showTip("当前音量:" + volume); showTip("当前音量:" + volume);
Log.d(TAG, "返回音频数据:"+data.length); Log.d(TAG, "返回音频数据:" + data.length);
} }
@Override @Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因 // 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
// if (SpeechEvent.EVENT_SESSION_ID == eventType) { // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid); // Log.d(TAG, "session id =" + sid);
// } // }
} }
}; };
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isedemo); setContentView(R.layout.isedemo);
mIse = SpeechEvaluator.createEvaluator(IseDemo.this, null); mIse = SpeechEvaluator.createEvaluator(IseDemo.this, null);
initUI(); initUI();
setEvaText(); setEvaText();
} }
private void initUI() { private void initUI() {
findViewById(R.id.image_ise_set).setOnClickListener(IseDemo.this); findViewById(R.id.image_ise_set).setOnClickListener(IseDemo.this);
mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text); mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text);
mResultEditText = (EditText)findViewById(R.id.ise_result_text); mResultEditText = (TextView) findViewById(R.id.ise_result_text);
mIseStartButton = (Button) findViewById(R.id.ise_start); mIseStartButton = (Button) findViewById(R.id.ise_start);
mIseStartButton.setOnClickListener(IseDemo.this); mIseStartButton.setOnClickListener(IseDemo.this);
findViewById(R.id.ise_parse).setOnClickListener(IseDemo.this); findViewById(R.id.ise_parse).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_stop).setOnClickListener(IseDemo.this); findViewById(R.id.ise_stop).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_cancel).setOnClickListener(IseDemo.this); findViewById(R.id.ise_cancel).setOnClickListener(IseDemo.this);
mToast = Toast.makeText(IseDemo.this, "", Toast.LENGTH_LONG); mToast = Toast.makeText(IseDemo.this, "", Toast.LENGTH_LONG);
} }
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if( null == mIse ){ if (null == mIse) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688 // 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" ); this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return; return;
} }
switch (view.getId()) { switch (view.getId()) {
case R.id.image_ise_set: case R.id.image_ise_set:
Intent intent = new Intent(IseDemo.this, IseSettings.class); Intent intent = new Intent(IseDemo.this, IseSettings.class);
startActivityForResult(intent, REQUEST_CODE_SETTINGS); startActivityForResult(intent, REQUEST_CODE_SETTINGS);
break; break;
case R.id.ise_start: case R.id.ise_start:
if (mIse == null) { if (mIse == null) {
return; return;
} }
String evaText = mEvaTextEditText.getText().toString(); String evaText = mEvaTextEditText.getText().toString();
mLastResult = null; mLastResult = null;
mResultEditText.setText(""); mResultEditText.setText("");
mResultEditText.setHint("请朗读以上内容"); mResultEditText.setHint("请朗读以上内容");
mIseStartButton.setEnabled(false); mIseStartButton.setEnabled(false);
setParams(); setParams();
int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener); int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener);
//以下方法为通过直接写入音频的方式进行评测业务 //以下方法为通过直接写入音频的方式进行评测业务
/*if (ret != ErrorCode.SUCCESS) { /*if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码:" + ret); showTip("识别失败,错误码:" + ret);
} else { } else {
@ -182,135 +181,181 @@ public class IseDemo extends Activity implements OnClickListener {
}*/ }*/
break; break;
case R.id.ise_parse: case R.id.ise_parse:
// 解析最终结果 // 解析最终结果
if (!TextUtils.isEmpty(mLastResult)) { if (!TextUtils.isEmpty(mLastResult)) {
XmlResultParser resultParser = new XmlResultParser(); // 拦截不支持的解析类型
Result result = resultParser.parse(mLastResult); if ("complete".equals(result_level)) {
if ("simple_expression".equals(category) || "read_choice".equals(category)
|| "topic".equals(category) || "retell".equals(category)
|| "picture_talk".equals(category) || "oral_translation".equals(category)) {
showTip("不支持解析该类型");
return;
}
}
if (null != result) { XmlResultParser resultParser = new XmlResultParser();
mResultEditText.setText(result.toString()); Result result = resultParser.parse(mLastResult);
} else {
showTip("解析结果为空");
}
}
break;
case R.id.ise_stop:
if (mIse.isEvaluating()) {
mResultEditText.setHint("评测已停止,等待结果中...");
mIse.stopEvaluating();
}
break;
case R.id.ise_cancel: {
mIse.cancel();
mIseStartButton.setEnabled(true);
mResultEditText.setText("");
mResultEditText.setHint("请点击“开始评测”按钮");
mLastResult = null;
break;
}
}
}
@Override if (null != result) {
protected void onActivityResult(int requestCode, int resultCode, Intent data) { mResultEditText.setText(result.toString());
super.onActivityResult(requestCode, resultCode, data); } else {
showTip("解析结果为空");
}
}
break;
case R.id.ise_stop:
if (mIse.isEvaluating()) {
mResultEditText.setHint("评测已停止,等待结果中...");
mIse.stopEvaluating();
}
break;
case R.id.ise_cancel: {
mIse.cancel();
mIseStartButton.setEnabled(true);
mResultEditText.setText("");
mResultEditText.setHint("请点击“开始评测”按钮");
mLastResult = null;
break;
}
}
}
if (REQUEST_CODE_SETTINGS == requestCode) { @Override
setEvaText(); protected void onActivityResult(int requestCode, int resultCode, Intent data) {
} super.onActivityResult(requestCode, resultCode, data);
}
@Override if (REQUEST_CODE_SETTINGS == requestCode) {
protected void onDestroy() { setEvaText();
super.onDestroy(); }
}
if (null != mIse) { @Override
mIse.destroy(); protected void onDestroy() {
mIse = null; super.onDestroy();
}
}
// 设置评测试题 if (null != mIse) {
private void setEvaText() { mIse.destroy();
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE); mIse = null;
language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn"); }
category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence"); }
String text = ""; // 设置评测试题
if ("en_us".equals(language)) { private void setEvaText() {
if ("read_word".equals(category)) { SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
text = getString(R.string.text_en_word); language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
} else if ("read_sentence".equals(category)) { category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
text = getString(R.string.text_en_sentence);
}
} else {
// 中文评测
if ("read_syllable".equals(category)) {
text = getString(R.string.text_cn_syllable);
} else if ("read_word".equals(category)) {
text = getString(R.string.text_cn_word);
} else if ("read_sentence".equals(category)) {
text = getString(R.string.text_cn_sentence);
}
}
mEvaTextEditText.setText(text); String text = "";
mResultEditText.setText(""); if ("en_us".equals(language)) {
mLastResult = null; switch (category) {
mResultEditText.setHint("请点击“开始评测”按钮"); case "read_word": // 词语
} text = getString(R.string.text_en_word);
break;
case "read_sentence": // 句子
text = getString(R.string.text_en_sentence);
break;
case "read_chapter": // 篇章
text = getString(R.string.text_en_chapter);
break;
case "simple_expression": // 英文情景反应
text = new String(Base64.decode(getString(R.string.text_en_simple_expression), Base64.DEFAULT));
break;
case "read_choice": // 英文选择题
text = new String(Base64.decode(getString(R.string.text_en_read_choice), Base64.DEFAULT));
break;
case "topic": // 英文自由题
text = new String(Base64.decode(getString(R.string.text_en_topic), Base64.DEFAULT));
break;
case "retell": // 英文复述题
text = new String(Base64.decode(getString(R.string.text_en_retell), Base64.DEFAULT));
break;
case "picture_talk": // 英文看图说话
text = new String(Base64.decode(getString(R.string.text_en_picture_talk), Base64.DEFAULT));
break;
case "oral_translation": // 英文口头翻译
text = new String(Base64.decode(getString(R.string.text_en_oral_translation), Base64.DEFAULT));
break;
}
private void showTip(String str) { } else {
if(!TextUtils.isEmpty(str)) { // 中文评测
mToast.setText(str); switch (category) {
mToast.show(); case "read_syllable":
} text = getString(R.string.text_cn_syllable);
} break;
private void setParams() { case "read_word":
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE); text = getString(R.string.text_cn_word);
// 设置评测语言 break;
language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn"); case "read_sentence":
// 设置需要评测的类型 text = getString(R.string.text_cn_sentence);
category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence"); break;
// 设置结果等级中文仅支持complete case "read_chapter":
result_level = pref.getString(SpeechConstant.RESULT_LEVEL, "complete"); text = getString(R.string.text_cn_chapter);
// 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理 break;
String vad_bos = pref.getString(SpeechConstant.VAD_BOS, "5000"); }
// 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音 }
String vad_eos = pref.getString(SpeechConstant.VAD_EOS, "1800");
// 语音输入超时时间即用户最多可以连续说多长时间
String speech_timeout = pref.getString(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
mIse.setParameter(SpeechConstant.LANGUAGE, language); mEvaTextEditText.setText(text);
mIse.setParameter(SpeechConstant.ISE_CATEGORY, category); mResultEditText.setText("");
mIse.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8"); mLastResult = null;
mIse.setParameter(SpeechConstant.VAD_BOS, vad_bos); mResultEditText.setHint("请点击“开始评测”按钮");
mIse.setParameter(SpeechConstant.VAD_EOS, vad_eos); }
mIse.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, speech_timeout);
mIse.setParameter(SpeechConstant.RESULT_LEVEL, result_level);
mIse.setParameter(SpeechConstant.AUDIO_FORMAT_AUE,"opus");
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
mIse.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
mIse.setParameter(SpeechConstant.ISE_AUDIO_PATH, Environment.getExternalStorageDirectory().getAbsolutePath() + "/msc/ise.wav");
//通过writeaudio方式直接写入音频时才需要此设置
//mIse.setParameter(SpeechConstant.AUDIO_SOURCE,"-1");
}
@Override private void showTip(String str) {
protected void onResume() { if (!TextUtils.isEmpty(str)) {
// 开放统计 移动数据统计分析 mToast.cancel();
/*FlowerCollector.onResume(IseDemo.this); mToast.setText(str);
FlowerCollector.onPageStart(TAG);*/ mToast.show();
super.onResume(); }
} }
private void setParams() {
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// 设置评测语言
language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
// 设置需要评测的类型
category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
// 设置结果等级中文仅支持complete
result_level = pref.getString(SpeechConstant.RESULT_LEVEL, "complete");
// 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理
String vad_bos = pref.getString(SpeechConstant.VAD_BOS, "5000");
// 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音
String vad_eos = pref.getString(SpeechConstant.VAD_EOS, "1800");
// 语音输入超时时间即用户最多可以连续说多长时间
String speech_timeout = pref.getString(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
// 设置流式版本所需参数 : ent sub plev
if ("zh_cn".equals(language)) {
mIse.setParameter("ent", "cn_vip");
}
if ("en_us".equals(language)) {
mIse.setParameter("ent", "en_vip");
}
mIse.setParameter(SpeechConstant.SUBJECT, "ise");
mIse.setParameter("plev", "0");
// 设置评分百分制 使用 ise_unite rst extra_ability 参数
mIse.setParameter("ise_unite", "1");
mIse.setParameter("rst", "entirety");
mIse.setParameter("extra_ability", "syll_phone_err_msg;pitch;multi_dimension");
mIse.setParameter(SpeechConstant.LANGUAGE, language);
mIse.setParameter(SpeechConstant.ISE_CATEGORY, category);
mIse.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
mIse.setParameter(SpeechConstant.VAD_BOS, vad_bos);
mIse.setParameter(SpeechConstant.VAD_EOS, vad_eos);
mIse.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, speech_timeout);
mIse.setParameter(SpeechConstant.RESULT_LEVEL, result_level);
mIse.setParameter(SpeechConstant.AUDIO_FORMAT_AUE, "opus");
// 设置音频保存路径保存音频格式支持pcmwav
mIse.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIse.setParameter(SpeechConstant.ISE_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/ise.wav");
//通过writeaudio方式直接写入音频时才需要此设置
//mIse.setParameter(SpeechConstant.AUDIO_SOURCE,"-1");
}
@Override
protected void onPause() {
/* // 开放统计 移动数据统计分析
FlowerCollector.onPageEnd(TAG);
FlowerCollector.onPause(IseDemo.this);*/
super.onPause();
}
} }

View File

@ -1,252 +1,84 @@
package com.iflytek.voicedemo; package com.iflytek.voicedemo;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.speech.setting.UrlSettings;
import com.iflytek.voicedemo.faceonline.OnlineFaceDemo;
import com.iflytek.voicedemo.vocalverify.VocalVerifyDemo;
import android.Manifest; import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window; import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import static com.iflytek.speech.setting.UrlSettings.PREFER_NAME; import androidx.core.app.ActivityCompat;
public class MainActivity extends Activity implements OnClickListener { public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName(); public void onCreate(Bundle savedInstanceState) {
private Toast mToast; super.onCreate(savedInstanceState);
private final int URL_REQUEST_CODE = 0X001; requestWindowFeature(Window.FEATURE_NO_TITLE);
private TextView edit_text; setContentView(R.layout.main);
initView();
requestPermissions();
}
@SuppressLint("ShowToast") private void initView() {
public void onCreate(Bundle savedInstanceState) { TextView tipTv = (TextView) findViewById(R.id.tip);
super.onCreate(savedInstanceState); String buf = "当前APPID为" +
requestWindowFeature(Window.FEATURE_NO_TITLE); getString(R.string.app_id) + "\n" +
setContentView(R.layout.main); getString(R.string.example_explain);
edit_text = (TextView) findViewById(R.id.edit_text); tipTv.setText(buf);
StringBuffer buf = new StringBuffer(); // 语音转写
buf.append("当前APPID为"); findViewById(R.id.iatBtn).setOnClickListener(v -> {
buf.append(getString(R.string.app_id)+"\n"); startActivity(new Intent(MainActivity.this, IatDemo.class));
buf.append(getString(R.string.example_explain)); });
edit_text.setText(buf); // 语法识别
requestPermissions(); findViewById(R.id.asrBtn).setOnClickListener(v -> {
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); startActivity(new Intent(MainActivity.this, AsrDemo.class));
//mscInit(null);//采用sdk默认url });
SimpleAdapter listitemAdapter = new SimpleAdapter(); // 语义理解
((ListView) findViewById(R.id.listview_main)).setAdapter(listitemAdapter); findViewById(R.id.nlpBtn).setOnClickListener(v -> {
showTip("请登录http://www.xfyun.cn/ 下载aiui体验吧");
});
// 语音合成
findViewById(R.id.ttsBtn).setOnClickListener(v -> {
startActivity(new Intent(MainActivity.this, TtsDemo.class));
});
// 语音评测
findViewById(R.id.iseBtn).setOnClickListener(v -> {
startActivity(new Intent(MainActivity.this, IseDemo.class));
});
// 人脸识别
findViewById(R.id.faceBtn).setOnClickListener(v -> {
showTip("请登录http://www.xfyun.cn/ “人脸识别”下载体验吧!");
});
}
private Toast mToast;
} private void showTip(final String str) {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
mToast.show();
}
@Override private void requestPermissions() {
public void onClick(View view) { try {
int tag = Integer.parseInt(view.getTag().toString()); if (Build.VERSION.SDK_INT >= 23) {
Intent intent = null; ActivityCompat.requestPermissions(this, new String[]{
switch (tag) { Manifest.permission.RECORD_AUDIO,
case 0: Manifest.permission.CAMERA
// 语音转写 }, 0x0010);
intent = new Intent(MainActivity.this, IatDemo.class); }
break; } catch (Exception e) {
case 1: e.printStackTrace();
// 语法识别 }
intent = new Intent(MainActivity.this, AsrDemo.class); }
break;
case 2:
// 语义理解
showTip("请登录http://www.xfyun.cn/ 下载aiui体验吧");
break;
case 3:
// 语音合成
intent = new Intent(MainActivity.this, TtsDemo.class);
break;
case 4:
// 语音评测
intent = new Intent(MainActivity.this, IseDemo.class);
break;
case 5:
// 唤醒
showTip("请登录http://www.xfyun.cn/ 下载体验吧!");
break;
case 6:
// 声纹
//intent = new Intent(MainActivity.this, VocalVerifyDemo.class);
showTip("请登录http://www.xfyun.cn/ “声纹识别”下载体验吧!");
break;
case 7:
//intent = new Intent(MainActivity.this,OnlineFaceDemo.class);
showTip("请登录http://www.xfyun.cn/ “人脸识别”下载体验吧!");
break;
/*case 8:
Intent init = new Intent(MainActivity.this, UrlSettings.class);
startActivityForResult(init, URL_REQUEST_CODE);
break;*/
default:
break;
}
if (intent != null) { @Override
startActivity(intent); public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
} super.onRequestPermissionsResult(requestCode, permissions, grantResults);
} }
// Menu 列表
String items[] = { "立刻体验语音听写", "立刻体验语法识别", "立刻体验语义理解", "立刻体验语音合成",
"立刻体验语音评测", "立刻体验语音唤醒", "立刻体验声纹密码","立刻体验人脸识别"/*,"重置域名"*/ };
private class SimpleAdapter extends BaseAdapter {
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
View mView = factory.inflate(R.layout.list_items, null);
convertView = mView;
}
Button btn = (Button) convertView.findViewById(R.id.btn);
btn.setOnClickListener(MainActivity.this);
btn.setTag(position);
btn.setText(items[position]);
return convertView;
}
@Override
public int getCount() {
return items.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
private void showTip(final String str) {
mToast.setText(str);
mToast.show();
}
@Override
protected void onResume() {
// 开放统计 移动数据统计分析
/*FlowerCollector.onResume(MainActivity.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
@Override
protected void onPause() {
// 开放统计 移动数据统计分析
/* FlowerCollector.onPageEnd(TAG);
FlowerCollector.onPause(MainActivity.this);*/
super.onPause();
}
private void requestPermissions(){
try {
if (Build.VERSION.SDK_INT >= 23) {
int permission = ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permission!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.LOCATION_HARDWARE,Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_SETTINGS,Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,Manifest.permission.READ_CONTACTS},0x0010);
}
if(permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},0x0010);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void mscInit (String serverUrl){
// 注意此接口在非主进程调用会返回null对象如需在非主进程使用语音功能请增加参数SpeechConstant.FORCE_LOGIN+"=true"
// 参数间使用半角,分隔
// 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
// 注意 appid 必须和下载的SDK保持一致否则会出现10407错误
StringBuffer bf = new StringBuffer();
bf.append("appid="+getString(R.string.app_id));
bf.append(",");
if (!TextUtils.isEmpty(serverUrl)) {
bf.append("server_url="+serverUrl);
bf.append(",");
}
//此处调用与SpeechDemo中重复两处只调用其一即可
SpeechUtility.createUtility(this.getApplicationContext(), bf.toString());
// 以下语句用于设置日志开关默认开启设置成false时关闭语音云SDK日志打印
// Setting.setShowLog(false);
}
private void mscUninit() {
if (SpeechUtility.getUtility()!= null) {
SpeechUtility.getUtility().destroy();
try{
new Thread().sleep(40);
}catch (InterruptedException e) {
Log.w(TAG,"msc uninit failed"+e.toString());
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (URL_REQUEST_CODE == requestCode) {
Log.d(TAG,"onActivityResult>>");
try{
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
String server_url = pref.getString("url_preference","");
String domain = pref.getString("url_edit","");
Log.d(TAG,"onActivityResult>>domain = "+domain);
if (!TextUtils.isEmpty(domain)) {
server_url = "http://"+domain+"/msp.do";
}
Log.d(TAG,"onActivityResult>>server_url = "+server_url);
mscUninit();
new Thread().sleep(40);
//mscInit(server_url);
}catch (Exception e) {
showTip("reset url failed");
}
}
}
} }

View File

@ -1,26 +1,27 @@
package com.iflytek.voicedemo; package com.iflytek.voicedemo;
import android.app.Application; import android.app.Application;
import com.iflytek.cloud.Setting; import com.iflytek.cloud.Setting;
import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SpeechUtility;
public class SpeechApp extends Application { public class SpeechApp extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
// 应用程序入口处调用避免手机内存过小杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null // 应用程序入口处调用避免手机内存过小杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
// 如在Application中调用初始化需要在Mainifest中注册该Applicaiton // 如在Application中调用初始化需要在Mainifest中注册该Applicaiton
// 注意此接口在非主进程调用会返回null对象如需在非主进程使用语音功能请增加参数SpeechConstant.FORCE_LOGIN+"=true" // 注意此接口在非主进程调用会返回null对象如需在非主进程使用语音功能请增加参数SpeechConstant.FORCE_LOGIN+"=true"
// 参数间使用半角,分隔 // 参数间使用半角,分隔
// 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符 // 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
// 注意 appid 必须和下载的SDK保持一致否则会出现10407错误 // 注意 appid 必须和下载的SDK保持一致否则会出现10407错误
SpeechUtility.createUtility(SpeechApp.this, "appid=" + getString(R.string.app_id)); SpeechUtility.createUtility(SpeechApp.this, "appid=" + getString(R.string.app_id));
// 以下语句用于设置日志开关默认开启设置成false时关闭语音云SDK日志打印 // 以下语句用于设置日志开关默认开启设置成false时关闭语音云SDK日志打印
// Setting.setShowLog(false); Setting.setShowLog(true);
super.onCreate(); super.onCreate();
} }
} }

View File

@ -1,6 +1,5 @@
package com.iflytek.voicedemo; package com.iflytek.voicedemo;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
@ -8,8 +7,6 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Color; import android.graphics.Color;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.os.MemoryFile;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan; import android.text.style.BackgroundColorSpan;
@ -29,368 +26,337 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent; import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener; import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.msc.util.FileUtil;
import com.iflytek.cloud.msc.util.log.DebugLog;
import com.iflytek.speech.setting.TtsSettings; import com.iflytek.speech.setting.TtsSettings;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.RandomAccessFile;
import java.util.Vector;
public class TtsDemo extends Activity implements OnClickListener { public class TtsDemo extends Activity implements OnClickListener {
private static String TAG = TtsDemo.class.getSimpleName(); private static String TAG = TtsDemo.class.getSimpleName();
// 语音合成对象 // 语音合成对象
private SpeechSynthesizer mTts; private SpeechSynthesizer mTts;
// 默认发音人 // 默认发音人
private String voicer = "xiaoyan"; private String voicer = "xiaoyan";
private String[] mCloudVoicersEntries; private String[] mCloudVoicersEntries;
private String[] mCloudVoicersValue ; private String[] mCloudVoicersValue;
String texts = ""; private String texts = "";
// 缓冲进度 // 缓冲进度
private int mPercentForBuffering = 0; private int mPercentForBuffering = 0;
// 播放进度 // 播放进度
private int mPercentForPlaying = 0; private int mPercentForPlaying = 0;
// 云端/本地单选按钮 // 云端/本地单选按钮
private RadioGroup mRadioGroup; private RadioGroup mRadioGroup;
// 引擎类型 // 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD; private String mEngineType = SpeechConstant.TYPE_CLOUD;
private Toast mToast; private Toast mToast;
private SharedPreferences mSharedPreferences; private SharedPreferences mSharedPreferences;
private File pcmFile;
MemoryFile memFile; public void onCreate(Bundle savedInstanceState) {
public volatile long mTotalSize = 0; super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.ttsdemo);
texts = getResources().getString(R.string.text_tts_source);
initLayout();
// 初始化合成对象
mTts = SpeechSynthesizer.createSynthesizer(TtsDemo.this, mTtsInitListener);
// 云端发音人名称列表
mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);
mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE);
}
private Vector<byte[]> container = new Vector<> (); /**
* 初始化Layout
*/
private void initLayout() {
findViewById(R.id.tts_play).setOnClickListener(TtsDemo.this);
findViewById(R.id.tts_cancel).setOnClickListener(TtsDemo.this);
findViewById(R.id.tts_pause).setOnClickListener(TtsDemo.this);
findViewById(R.id.tts_resume).setOnClickListener(TtsDemo.this);
findViewById(R.id.image_tts_set).setOnClickListener(TtsDemo.this);
findViewById(R.id.tts_btn_person_select).setOnClickListener(TtsDemo.this);
@SuppressLint("ShowToast") mRadioGroup = ((RadioGroup) findViewById(R.id.tts_rediogroup));
public void onCreate(Bundle savedInstanceState) { mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.ttsdemo);
texts = getResources().getString(R.string.text_tts_source);
initLayout();
DebugLog.setShowLog(true);
// 初始化合成对象
mTts = SpeechSynthesizer.createSynthesizer(TtsDemo.this, mTtsInitListener);
// 云端发音人名称列表 @Override
mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries); public void onCheckedChanged(RadioGroup group, int checkedId) {
mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values); switch (checkedId) {
case R.id.tts_radioCloud:
mEngineType = SpeechConstant.TYPE_CLOUD;
break;
default:
break;
}
mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE); }
mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT); });
}
} @Override
public void onClick(View view) {
if (null == mTts) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return;
}
/** switch (view.getId()) {
* 初始化Layout case R.id.image_tts_set:
*/ if (SpeechConstant.TYPE_CLOUD.equals(mEngineType)) {
private void initLayout() { Intent intent = new Intent(TtsDemo.this, TtsSettings.class);
findViewById(R.id.tts_play).setOnClickListener(TtsDemo.this); startActivity(intent);
findViewById(R.id.tts_cancel).setOnClickListener(TtsDemo.this); } else {
findViewById(R.id.tts_pause).setOnClickListener(TtsDemo.this); showTip("请前往xfyun.cn下载离线合成体验");
findViewById(R.id.tts_resume).setOnClickListener(TtsDemo.this); }
findViewById(R.id.image_tts_set).setOnClickListener(TtsDemo.this); break;
findViewById(R.id.tts_btn_person_select).setOnClickListener(TtsDemo.this); // 开始合成
// 收到onCompleted 回调时合成结束生成合成音频
mRadioGroup=((RadioGroup) findViewById(R.id.tts_rediogroup)); // 合成的音频格式只支持pcm格式
mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { case R.id.tts_play:
pcmFile = new File(getExternalCacheDir().getAbsolutePath(), "tts_pcmFile.pcm");
@Override pcmFile.delete();
public void onCheckedChanged(RadioGroup group, int checkedId) { texts = ((EditText) findViewById(R.id.tts_text)).getText().toString();
switch (checkedId) { // 设置参数
case R.id.tts_radioCloud: setParam();
mEngineType = SpeechConstant.TYPE_CLOUD; // 合成并播放
break; int code = mTts.startSpeaking(texts, mTtsListener);
default:
break;
}
}
} );
}
@Override
public void onClick(View view) {
if( null == mTts ){
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" );
return;
}
switch(view.getId()) {
case R.id.image_tts_set:
if(SpeechConstant.TYPE_CLOUD.equals(mEngineType)){
Intent intent = new Intent(TtsDemo.this, TtsSettings.class);
startActivity(intent);
}else{
showTip("请前往xfyun.cn下载离线合成体验");
}
break;
// 开始合成
// 收到onCompleted 回调时合成结束生成合成音频
// 合成的音频格式只支持pcm格式
case R.id.tts_play:
// 移动数据分析收集开始合成事件
/*FlowerCollector.onEvent(TtsDemo.this, "tts_play");*/
texts = ((EditText) findViewById(R.id.tts_text)).getText().toString();
// 设置参数
setParam();
int code = mTts.startSpeaking(texts, mTtsListener);
// /** // /**
// * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口 // * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
// * text:要合成的文本uri:需要保存的音频全路径listener:回调接口 // * text:要合成的文本uri:需要保存的音频全路径listener:回调接口
// */ // */
String path = Environment.getExternalStorageDirectory()+"/tts.pcm"; // String path = getExternalFilesDir("msc").getAbsolutePath() + "/tts.pcm";
// int code = mTts.synthesizeToUri(texts, path, mTtsListener); // // synthesizeToUri 只保存音频不进行播放
// int code = mTts.synthesizeToUri(texts, path, mTtsListener);
if (code != ErrorCode.SUCCESS) { if (code != ErrorCode.SUCCESS) {
showTip("语音合成失败,错误码: " + code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); showTip("语音合成失败,错误码: " + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} }
break; break;
// 取消合成 // 取消合成
case R.id.tts_cancel: case R.id.tts_cancel:
mTts.stopSpeaking(); mTts.stopSpeaking();
break; break;
// 暂停播放 // 暂停播放
case R.id.tts_pause: case R.id.tts_pause:
mTts.pauseSpeaking(); mTts.pauseSpeaking();
break; break;
// 继续播放 // 继续播放
case R.id.tts_resume: case R.id.tts_resume:
mTts.resumeSpeaking(); mTts.resumeSpeaking();
break; break;
// 选择发音人 // 选择发音人
case R.id.tts_btn_person_select: case R.id.tts_btn_person_select:
showPresonSelectDialog(); showPersonSelectDialog();
break; break;
} }
} }
private int selectedNum = 0;
/**
* 发音人选择
*/
private void showPresonSelectDialog() {
switch (mRadioGroup.getCheckedRadioButtonId()) {
// 选择在线合成
case R.id.tts_radioCloud:
new AlertDialog.Builder(this).setTitle("在线合成发音人选项")
.setSingleChoiceItems(mCloudVoicersEntries, // 单选框有几项,各是什么名字
selectedNum, // 默认的选项
new DialogInterface.OnClickListener() { // 点击单选框后的处理
public void onClick(DialogInterface dialog,
int which) { // 点击了哪一项
voicer = mCloudVoicersValue[which];
if ("catherine".equals(voicer) || "henry".equals(voicer) || "vimary".equals(voicer)) {
((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source_en);
}else {
((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source);
}
selectedNum = which;
dialog.dismiss();
}
}).show();
break;
default: private int selectedNum = 0;
break;
}
}
/** /**
* 初始化监听 * 发音人选择
*/ */
private InitListener mTtsInitListener = new InitListener() { private void showPersonSelectDialog() {
@Override switch (mRadioGroup.getCheckedRadioButtonId()) {
public void onInit(int code) { // 选择在线合成
Log.d(TAG, "InitListener init() code = " + code); case R.id.tts_radioCloud:
if (code != ErrorCode.SUCCESS) { new AlertDialog.Builder(this).setTitle("在线合成发音人选项")
showTip("初始化失败,错误码:"+code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); .setSingleChoiceItems(mCloudVoicersEntries, // 单选框有几项,各是什么名字
} else { selectedNum, // 默认的选项
// 初始化成功之后可以调用startSpeaking方法 new DialogInterface.OnClickListener() { // 点击单选框后的处理
// 有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成 public void onClick(DialogInterface dialog,
// 正确的做法是将onCreate中的startSpeaking调用移至这里 int which) { // 点击了哪一项
} voicer = mCloudVoicersValue[which];
} if ("catherine".equals(voicer) || "henry".equals(voicer) || "vimary".equals(voicer)) {
}; ((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source_en);
} else {
((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source);
}
selectedNum = which;
dialog.dismiss();
}
}).show();
break;
/** default:
* 合成回调监听 break;
*/ }
private SynthesizerListener mTtsListener = new SynthesizerListener() { }
@Override /**
public void onSpeakBegin() { * 初始化监听
showTip("开始播放"); */
} private InitListener mTtsInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d(TAG, "InitListener init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} else {
// 初始化成功之后可以调用startSpeaking方法
// 有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成
// 正确的做法是将onCreate中的startSpeaking调用移至这里
}
}
};
@Override /**
public void onSpeakPaused() { * 合成回调监听
showTip("暂停播放"); */
} private SynthesizerListener mTtsListener = new SynthesizerListener() {
@Override @Override
public void onSpeakResumed() { public void onSpeakBegin() {
showTip("继续播放"); showTip("开始播放");
} }
@Override @Override
public void onBufferProgress(int percent, int beginPos, int endPos, public void onSpeakPaused() {
String info) { showTip("暂停播放");
// 合成进度 }
Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override @Override
public void onSpeakProgress(int percent, int beginPos, int endPos) { public void onSpeakResumed() {
// 播放进度 showTip("继续播放");
Log.e("MscSpeechLog_", "percent =" + percent); }
mPercentForPlaying = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
SpannableStringBuilder style=new SpannableStringBuilder(texts); @Override
Log.e(TAG,"beginPos = "+beginPos +" endPos = "+endPos); public void onBufferProgress(int percent, int beginPos, int endPos,
style.setSpan(new BackgroundColorSpan(Color.RED),beginPos,endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String info) {
((EditText) findViewById(R.id.tts_text)).setText(style); // 合成进度
} Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override @Override
public void onCompleted(SpeechError error) { public void onSpeakProgress(int percent, int beginPos, int endPos) {
System.out.println("oncompleted"); // 播放进度
if (error == null) { Log.e("MscSpeechLog_", "percent =" + percent);
// showTip("播放完成"); mPercentForPlaying = percent;
DebugLog.LogD("播放完成,"+container.size()); showTip(String.format(getString(R.string.tts_toast_format),
try { mPercentForBuffering, mPercentForPlaying));
for(int i=0;i<container.size();i++) {
writeToFile(container.get(i));
}
}catch (IOException e) {
} SpannableStringBuilder style = new SpannableStringBuilder(texts);
FileUtil.saveFile(memFile,mTotalSize,Environment.getExternalStorageDirectory()+"/1.pcm"); Log.e(TAG, "beginPos = " + beginPos + " endPos = " + endPos);
style.setSpan(new BackgroundColorSpan(Color.RED), beginPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((EditText) findViewById(R.id.tts_text)).setText(style);
}
@Override
public void onCompleted(SpeechError error) {
showTip("播放完成");
if (error != null) {
showTip(error.getPlainDescription(true));
return;
}
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
// 若使用本地能力会话id为null
if (SpeechEvent.EVENT_SESSION_ID == eventType) {
String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
Log.d(TAG, "session id =" + sid);
}
// 当设置 SpeechConstant.TTS_DATA_NOTIFY 为1时抛出buf数据
if (SpeechEvent.EVENT_TTS_BUFFER == eventType) {
byte[] buf = obj.getByteArray(SpeechEvent.KEY_EVENT_TTS_BUFFER);
Log.e(TAG, "EVENT_TTS_BUFFER = " + buf.length);
// 保存文件
appendFile(pcmFile, buf);
}
}
};
private void showTip(final String str) {
runOnUiThread(() -> {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
mToast.show();
});
}
/**
* 参数设置
*
* @return
*/
private void setParam() {
// 清空参数
mTts.setParameter(SpeechConstant.PARAMS, null);
// 根据合成引擎设置相应参数
if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
// 支持实时音频返回仅在 synthesizeToUri 条件下支持
mTts.setParameter(SpeechConstant.TTS_DATA_NOTIFY, "1");
// mTts.setParameter(SpeechConstant.TTS_BUFFER_TIME,"1");
// 设置在线合成发音人
mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
//设置合成语速
mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
//设置合成音调
mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
//设置合成音量
mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
} else {
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
mTts.setParameter(SpeechConstant.VOICE_NAME, "");
}
//设置播放器音频流类型
mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
// 设置播放合成音频打断音乐播放默认为true
mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "false");
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "pcm");
mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/tts.pcm");
}
@Override
protected void onDestroy() {
if (null != mTts) {
mTts.stopSpeaking();
// 退出时释放连接
mTts.destroy();
}
super.onDestroy();
}
} else if (error != null) { /**
showTip(error.getPlainDescription(true)); * 给file追加数据
} */
} private void appendFile(File file, byte[] buffer) {
try {
@Override if (!file.exists()) {
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { boolean b = file.createNewFile();
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因 }
// 若使用本地能力会话id为null RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
if (SpeechEvent.EVENT_SESSION_ID == eventType) { randomFile.seek(file.length());
String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); randomFile.write(buffer);
Log.d(TAG, "session id =" + sid); randomFile.close();
} } catch (IOException e) {
e.printStackTrace();
//当设置SpeechConstant.TTS_DATA_NOTIFY为1时抛出buf数据 }
if (SpeechEvent.EVENT_TTS_BUFFER == eventType) { }
byte[] buf = obj.getByteArray(SpeechEvent.KEY_EVENT_TTS_BUFFER);
Log.e("MscSpeechLog_", "bufis =" + buf.length);
container.add(buf);
}
}
};
private void showTip(final String str) {
Toast.makeText(this,str,Toast.LENGTH_SHORT);
}
/**
* 参数设置
* @return
*/
private void setParam(){
// 清空参数
mTts.setParameter(SpeechConstant.PARAMS, null);
// 根据合成引擎设置相应参数
if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
//支持实时音频返回仅在synthesizeToUri条件下支持
mTts.setParameter(SpeechConstant.TTS_DATA_NOTIFY, "1");
// mTts.setParameter(SpeechConstant.TTS_BUFFER_TIME,"1");
// 设置在线合成发音人
mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
//设置合成语速
mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
//设置合成音调
mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
//设置合成音量
mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
}else {
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
mTts.setParameter(SpeechConstant.VOICE_NAME, "");
}
//设置播放器音频流类型
mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
// 设置播放合成音频打断音乐播放默认为true
mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "false");
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "pcm");
mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.pcm");
}
@Override
protected void onDestroy() {
super.onDestroy();
if( null != mTts ){
mTts.stopSpeaking();
// 退出时释放连接
mTts.destroy();
}
}
@Override
protected void onResume() {
//移动数据统计分析
/*FlowerCollector.onResume(TtsDemo.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
@Override
protected void onPause() {
//移动数据统计分析
/*FlowerCollector.onPageEnd(TAG);
FlowerCollector.onPause(TtsDemo.this);*/
super.onPause();
}
private void writeToFile(byte[] data) throws IOException {
if (data == null || data.length == 0)
return;
try {
if(memFile == null)
{
Log.e("MscSpeechLog_","ffffffffff");
String mFilepath = Environment.getExternalStorageDirectory()+"/1.pcm";
memFile = new MemoryFile(mFilepath,1920000);
memFile.allowPurging(false);
}
memFile.writeBytes(data, 0, (int)mTotalSize, data.length);
mTotalSize += data.length;
} finally {
}
}
} }

View File

@ -5,13 +5,12 @@ import android.app.Activity;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection; import android.media.MediaScannerConnection;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.SystemClock;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
@ -19,7 +18,6 @@ import android.view.View;
import android.view.Window; import android.view.Window;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.ErrorCode;
@ -29,11 +27,9 @@ import com.iflytek.cloud.IdentityVerifier;
import com.iflytek.cloud.InitListener; import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.speech.util.FaceUtil; import com.iflytek.speech.util.FaceUtil;
import com.iflytek.voicedemo.IdentifyGroup.GroupManagerActivity; import com.iflytek.voicedemo.IdentifyGroup.GroupManagerActivity;
import com.iflytek.voicedemo.R; import com.iflytek.voicedemo.R;
import com.iflytek.voicedemo.vocalverify.VocalVerifyDemo;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -42,18 +38,14 @@ import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
/** /**
*
* 此demo意在为提供在线人脸识别相关api调用方式1:1 识别 * 此demo意在为提供在线人脸识别相关api调用方式1:1 识别
* *
* @author hjyu * @author hjyu
* @date 2017/9/28. * @date 2017/9/28.
* @see <a href="http://www.xfyun.cn">讯飞开放平台</a> * @see <a href="http://www.xfyun.cn">讯飞开放平台</a>
*/ */
public class OnlineFaceDemo extends Activity implements View.OnClickListener { public class OnlineFaceDemo extends Activity implements View.OnClickListener {
private final String TAG = "OnlineFaceDemo"; private final String TAG = "OnlineFaceDemo";
private final int REQUEST_PICTURE_CHOOSE = 1;
private final int REQUEST_CAMERA_IMAGE = 2;
private Bitmap mImage = null; private Bitmap mImage = null;
private byte[] mImageData = null; private byte[] mImageData = null;
@ -112,7 +104,7 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
if (ErrorCode.SUCCESS == errorCode) { if (ErrorCode.SUCCESS == errorCode) {
showTip("引擎初始化成功"); showTip("引擎初始化成功");
} else { } else {
showTip("引擎初始化失败,错误码:" + errorCode+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案"); showTip("引擎初始化失败,错误码:" + errorCode + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
} }
} }
}); });
@ -149,8 +141,6 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
} }
/** /**
* 人脸注册监听器 * 人脸注册监听器
*/ */
@ -170,7 +160,7 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
if (ErrorCode.SUCCESS == ret) { if (ErrorCode.SUCCESS == ret) {
showTip("注册成功"); showTip("注册成功");
}else { } else {
showTip(new SpeechError(ret).getPlainDescription(true)); showTip(new SpeechError(ret).getPlainDescription(true));
} }
} catch (JSONException e) { } catch (JSONException e) {
@ -208,7 +198,7 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
try { try {
JSONObject object = new JSONObject(result.getResultString()); JSONObject object = new JSONObject(result.getResultString());
Log.d(TAG,"object is: "+object.toString()); Log.d(TAG, "object is: " + object.toString());
String decision = object.getString("decision"); String decision = object.getString("decision");
if ("accepted".equalsIgnoreCase(decision)) { if ("accepted".equalsIgnoreCase(decision)) {
@ -281,7 +271,6 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
}; };
private void executeModelCommand(String cmd) { private void executeModelCommand(String cmd) {
// 设置模型参数若无可以传空字符传 // 设置模型参数若无可以传空字符传
StringBuffer params = new StringBuffer(); StringBuffer params = new StringBuffer();
@ -293,10 +282,10 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
public void onClick(View view) { public void onClick(View view) {
int ret = ErrorCode.SUCCESS; int ret = ErrorCode.SUCCESS;
mAuthid = online_authid.getText().toString(); mAuthid = online_authid.getText().toString();
if(TextUtils.isEmpty(mAuthid)) { if (TextUtils.isEmpty(mAuthid)) {
showTip("请输入用户ID"); showTip("请输入用户ID");
return; return;
}else { } else {
online_authid.setEnabled(false); online_authid.setEnabled(false);
} }
@ -305,7 +294,7 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setType("image/*"); intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK); intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICTURE_CHOOSE); startActivityForResult(intent, FaceUtil.REQUEST_PICTURE_CHOOSE);
break; break;
case R.id.online_reg: case R.id.online_reg:
if (TextUtils.isEmpty(mAuthid)) { if (TextUtils.isEmpty(mAuthid)) {
@ -376,15 +365,8 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
break; break;
case R.id.online_camera: case R.id.online_camera:
// 设置相机拍照后照片保存路径
mPictureFile = new File(Environment.getExternalStorageDirectory(),
"picture" + System.currentTimeMillis()/1000 + ".jpg");
// 启动拍照,并保存到临时文件 // 启动拍照,并保存到临时文件
Intent mIntent = new Intent(); takePhoto();
mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile));
mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
startActivityForResult(mIntent, REQUEST_CAMERA_IMAGE);
break; break;
case R.id.btn_modle_delete: case R.id.btn_modle_delete:
// 人脸模型删除 // 人脸模型删除
@ -392,61 +374,60 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
executeModelCommand("delete"); executeModelCommand("delete");
break; break;
case R.id.btn_identity: case R.id.btn_identity:
Intent init = new Intent(OnlineFaceDemo.this, GroupManagerActivity.class); Intent init = new Intent(OnlineFaceDemo.this, GroupManagerActivity.class);
init.putExtra("auth_id",mAuthid); init.putExtra("auth_id", mAuthid);
init.putExtra("mfv_scenes","ifr"); init.putExtra("mfv_scenes", "ifr");
startActivity(init); startActivity(init);
break; break;
default: default:
break; break;
}//end of switch }//end of switch
if( ErrorCode.SUCCESS != ret ){ if (ErrorCode.SUCCESS != ret) {
mProDialog.dismiss(); mProDialog.dismiss();
showTip( "出现错误:"+ret ); showTip("出现错误:" + ret);
} }
} }
private void takePhoto() {
// 设置相机拍照后照片保存路径
mPictureFile = new File(getExternalFilesDir("msc").getAbsolutePath(),
"picture_" + SystemClock.uptimeMillis() + ".jpg");
if (mPictureFile.exists()) {
mPictureFile.delete();
}
Uri imageUri = FaceUtil.parseUri(getApplication(), mPictureFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, FaceUtil.REQUEST_CAMERA_IMAGE);
}
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { if (resultCode != RESULT_OK) {
return; return;
} }
String fileSrc = null; String fileSrc = null;
if (requestCode == REQUEST_PICTURE_CHOOSE) { // 选择文件
if ("file".equals(data.getData().getScheme())) { if (requestCode == FaceUtil.REQUEST_PICTURE_CHOOSE) {
// 有些低版本机型返回的Uri模式为file
fileSrc = data.getData().getPath();
} else {
// Uri模型为content
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(data.getData(), proj,
null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileSrc = cursor.getString(idx);
cursor.close();
}
// 跳转到图片裁剪页面 // 跳转到图片裁剪页面
FaceUtil.cropPicture(this,Uri.fromFile(new File(fileSrc))); FaceUtil.cropPicture(this, data.getData());
} else if (requestCode == REQUEST_CAMERA_IMAGE) { return;
if (null == mPictureFile) { }
// 拍照
if (requestCode == FaceUtil.REQUEST_CAMERA_IMAGE) {
if (null == mPictureFile || !mPictureFile.exists()) {
showTip("拍照失败,请重试"); showTip("拍照失败,请重试");
return; return;
} }
fileSrc = mPictureFile.getAbsolutePath();
updateGallery(fileSrc);
// 跳转到图片裁剪页面 // 跳转到图片裁剪页面
FaceUtil.cropPicture(this,Uri.fromFile(new File(fileSrc))); FaceUtil.cropPicture(
} else if (requestCode == FaceUtil.REQUEST_CROP_IMAGE) { OnlineFaceDemo.this,
// 获取返回数据 FaceUtil.parseUri(getApplication(), mPictureFile));
Bitmap bmp = data.getParcelableExtra("data"); return;
// 若返回数据不为null保存至本地防止裁剪时未能正常保存 }
if(null != bmp){ // 裁剪
FaceUtil.saveBitmapToFile(OnlineFaceDemo.this, bmp); if (requestCode == FaceUtil.REQUEST_CROP_IMAGE) {
}
// 获取图片保存路径 // 获取图片保存路径
fileSrc = FaceUtil.getImagePath(OnlineFaceDemo.this); fileSrc = FaceUtil.getImagePath(OnlineFaceDemo.this);
// 获取图片的宽和高 // 获取图片的宽和高
@ -461,29 +442,23 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
options.inJustDecodeBounds = false; options.inJustDecodeBounds = false;
mImage = BitmapFactory.decodeFile(fileSrc, options); mImage = BitmapFactory.decodeFile(fileSrc, options);
// 若mImageBitmap为空则图片信息不能正常获取 // 若mImageBitmap为空则图片信息不能正常获取
if(null == mImage) { if (null == mImage) {
showTip("图片信息无法正常获取!"); showTip("图片信息无法正常获取!");
return; return;
} }
// 部分手机会对图片做旋转这里检测旋转角度 // 部分手机会对图片做旋转这里检测旋转角度
int degree = FaceUtil.readPictureDegree(fileSrc); int degree = FaceUtil.readPictureDegree(fileSrc);
if (degree != 0) { if (degree != 0) {
// 把图片旋转为正的方向 // 把图片旋转为正的方向
mImage = FaceUtil.rotateImage(degree, mImage); mImage = FaceUtil.rotateImage(degree, mImage);
} }
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
//可根据流量及网络状况对图片进行压缩 //可根据流量及网络状况对图片进行压缩
mImage.compress(Bitmap.CompressFormat.JPEG, 80, baos); mImage.compress(Bitmap.CompressFormat.JPEG, 80, baos);
mImageData = baos.toByteArray(); mImageData = baos.toByteArray();
((ImageView) findViewById(R.id.online_img)).setImageBitmap(mImage); ((ImageView) findViewById(R.id.online_img)).setImageBitmap(mImage);
} }
} }
@Override @Override
@ -495,9 +470,8 @@ public class OnlineFaceDemo extends Activity implements View.OnClickListener {
} }
private void updateGallery(String filename) { private void updateGallery(String filename) {
MediaScannerConnection.scanFile(this, new String[] {filename}, null, MediaScannerConnection.scanFile(this, new String[]{filename}, null,
new MediaScannerConnection.OnScanCompletedListener() { new MediaScannerConnection.OnScanCompletedListener() {
@Override @Override
public void onScanCompleted(String path, Uri uri) { public void onScanCompleted(String path, Uri uri) {

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<selector <selector xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/list_backgroud_color"></item> <item android:state_pressed="true" android:drawable="@color/list_backgroud_color"></item>
<item android:drawable="@drawable/layout_backgroud"></item> <item android:drawable="@drawable/layout_backgroud"></item>
</selector> </selector>

View File

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/setting" android:state_focused="true" android:state_pressed="false"/> <item android:drawable="@drawable/setting" android:state_focused="true" android:state_pressed="false" />
<item android:drawable="@drawable/setting_p" android:state_focused="true" android:state_pressed="true"/> <item android:drawable="@drawable/setting_p" android:state_focused="true" android:state_pressed="true" />
<item android:drawable="@drawable/setting_p" android:state_focused="false" android:state_pressed="true"/> <item android:drawable="@drawable/setting_p" android:state_focused="false" android:state_pressed="true" />
<item android:drawable="@drawable/setting"></item> <item android:drawable="@drawable/setting"></item>
</selector> </selector>

View File

@ -1,85 +1,83 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:focusable="true" android:focusable="true"
android:focusableInTouchMode="true" android:focusableInTouchMode="true"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:padding="10dp" > android:padding="10dp">
<TextView <TextView
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:text="@string/title_face_idf" android:text="@string/title_face_idf"
android:textSize="30sp" /> android:textSize="30sp" />
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:layout_weight="1" android:layout_weight="1"
android:gravity="center" > android:gravity="center">
<ImageView <ImageView
android:id="@+id/online_img" android:id="@+id/online_img"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:padding="4dp" android:padding="4dp"
android:src="@drawable/no_photo" /> android:src="@drawable/no_photo" />
</LinearLayout> </LinearLayout>
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/txt_groupid" android:id="@+id/txt_groupid"
android:layout_gravity="center_horizontal" android:layout_gravity="center_horizontal"
android:padding="5dp"/> android:padding="5dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="@+id/online_pick"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="选图"
android:textSize="20sp" />
<Button
android:id="@+id/online_camera"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="拍照"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/online_pick" android:id="@+id/btn_identity"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1"
android:text="选图" android:text="1:N验证"
android:textSize="20sp" /> android:textSize="20sp" />
</LinearLayout>
<Button
android:id="@+id/online_camera"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="拍照"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_identity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1:N验证"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout> </LinearLayout>

View File

@ -1,8 +1,7 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/group_manager_layout" android:id="@+id/group_manager_layout"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" > android:layout_height="match_parent">
<ListView <ListView
android:id="@+id/lv_my_group" android:id="@+id/lv_my_group"

View File

@ -3,7 +3,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" > android:orientation="vertical">
<!-- 标题栏 --> <!-- 标题栏 -->
<RelativeLayout <RelativeLayout
@ -19,39 +19,39 @@
android:layout_height="30dp" android:layout_height="30dp"
android:gravity="center" android:gravity="center"
android:textSize="26sp" android:textSize="26sp"
android:text="1:N验证结果"/> android:text="1:N验证结果" />
</RelativeLayout> </RelativeLayout>
<RelativeLayout <RelativeLayout
android:id="@+id/idf_result_layout" android:id="@+id/idf_result_layout"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical" > android:orientation="vertical">
<LinearLayout <LinearLayout
android:id="@+id/lly_group_name" android:id="@+id/lly_group_name"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp" android:layout_marginBottom="20dp"
android:layout_marginTop="30dp" android:layout_marginTop="30dp"
android:orientation="horizontal" > android:orientation="horizontal">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="组名称:" android:text="组名称:"
android:textColor="@color/white" android:textColor="@color/white"
android:textSize="20sp" /> android:textSize="20sp" />
<TextView <TextView
android:id="@+id/txt_group_name" android:id="@+id/txt_group_name"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="10dp" android:layout_marginLeft="10dp"
android:textColor="@color/white" android:textColor="@color/white"
android:textSize="20sp" /> android:textSize="20sp" />
</LinearLayout> </LinearLayout>
<TextView <TextView
android:id="@+id/txt_hint" android:id="@+id/txt_hint"
@ -74,8 +74,7 @@
android:layout_alignLeft="@id/txt_hint" android:layout_alignLeft="@id/txt_hint"
android:fadingEdge="none" android:fadingEdge="none"
android:cacheColorHint="#00000000" android:cacheColorHint="#00000000"
android:listSelector="#00000000" > android:listSelector="#00000000"></ListView>
</ListView>
</RelativeLayout> </RelativeLayout>
</LinearLayout> </LinearLayout>

View File

@ -1,5 +1,4 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/group_manager_layout" android:id="@+id/group_manager_layout"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent">
@ -10,7 +9,7 @@
android:id="@+id/rllyt_title" android:id="@+id/rllyt_title"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="50dp" android:layout_height="50dp"
android:gravity="center_vertical" > android:gravity="center_vertical">
<TextView <TextView
android:id="@+id/txt_login_title" android:id="@+id/txt_login_title"
@ -29,12 +28,12 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="20dp" android:layout_marginTop="20dp"
android:orientation="horizontal" android:orientation="horizontal"
android:gravity="center" > android:gravity="center">
<ImageView <ImageView
android:layout_width="17dp" android:layout_width="17dp"
android:layout_height="18dp" android:layout_height="18dp"
android:src="@drawable/user" /> android:src="@drawable/user" />
<TextView <TextView
android:id="@+id/txt_username" android:id="@+id/txt_username"
@ -53,7 +52,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/user_info_layout" android:layout_below="@id/user_info_layout"
android:layout_marginTop="25dp" android:layout_marginTop="25dp"
android:paddingBottom="10dp" > android:paddingBottom="10dp">
<View <View
android:id="@+id/line_create" android:id="@+id/line_create"
@ -70,7 +69,7 @@
android:layout_marginLeft="10dp" android:layout_marginLeft="10dp"
android:layout_marginRight="5dp" android:layout_marginRight="5dp"
android:orientation="vertical" android:orientation="vertical"
android:visibility="visible" > android:visibility="visible">
<EditText <EditText
android:id="@+id/edt_group_name" android:id="@+id/edt_group_name"
@ -82,132 +81,131 @@
android:hint="请输入组名用于创建组..." android:hint="请输入组名用于创建组..."
android:inputType="text" android:inputType="text"
android:paddingLeft="5dp" android:paddingLeft="5dp"
android:textSize="18sp" > android:textSize="18sp"></EditText>
</EditText>
</LinearLayout> </LinearLayout>
<Button <Button
android:id="@+id/btn_group_create" android:id="@+id/btn_group_create"
android:layout_width="250dp" android:layout_width="250dp"
android:layout_height="48dp" android:layout_height="48dp"
android:layout_below="@id/line_create" android:layout_below="@id/line_create"
android:layout_marginRight="10dp" android:layout_marginRight="10dp"
android:gravity="center" android:gravity="center"
android:layout_toRightOf="@id/llyt_groupname_input_panel" android:layout_toRightOf="@id/llyt_groupname_input_panel"
android:text="创建" /> android:text="创建" />
</RelativeLayout> </RelativeLayout>
<RelativeLayout <RelativeLayout
android:id="@+id/group_add_layout" android:id="@+id/group_add_layout"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@+id/group_create_layout" android:layout_below="@+id/group_create_layout"
android:layout_centerHorizontal="true" android:layout_centerHorizontal="true"
android:layout_marginTop="51dp" android:layout_marginTop="51dp"
android:paddingBottom="20dp"> android:paddingBottom="20dp">
<View <View
android:id="@+id/line_add" android:id="@+id/line_add"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="1dip" android:layout_height="1dip"
android:layout_alignParentTop="true" android:layout_alignParentTop="true"
android:layout_margin="10dp" android:layout_margin="10dp"
android:background="#e5e5e6" /> android:background="#e5e5e6" />
<LinearLayout <LinearLayout
android:id="@+id/llyt_groupid_input_panel" android:id="@+id/llyt_groupid_input_panel"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/line_add" android:layout_below="@id/line_add"
android:layout_marginLeft="10dp" android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" android:layout_marginRight="10dp"
android:orientation="vertical" android:orientation="vertical"
android:visibility="visible"> android:visibility="visible">
<EditText <EditText
android:id="@+id/edt_group_id" android:id="@+id/edt_group_id"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="35dp" android:layout_height="35dp"
android:background="#00000000" android:background="#00000000"
android:digits="0123456789abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ_" android:digits="0123456789abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ_"
android:ems="20" android:ems="20"
android:gravity="center_vertical" android:gravity="center_vertical"
android:hint="请输入组ID..." android:hint="请输入组ID..."
android:inputType="text" android:inputType="text"
android:paddingLeft="5dp" android:paddingLeft="5dp"
android:singleLine="true" android:singleLine="true"
android:textSize="18sp"></EditText> android:textSize="18sp"></EditText>
</LinearLayout> </LinearLayout>
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/llyt_groupid_input_panel" android:layout_below="@id/llyt_groupid_input_panel"
android:layout_marginLeft="10dp" android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" android:layout_marginRight="10dp"
android:orientation="horizontal" android:orientation="horizontal"
android:paddingTop="25dp" android:paddingTop="25dp"
android:weightSum="3"> android:weightSum="3">
<Button <Button
android:id="@+id/btn_group_join" android:id="@+id/btn_group_join"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="48dp" android:layout_height="48dp"
android:layout_weight="1" android:layout_weight="1"
android:gravity="center" android:gravity="center"
android:text="加入组" /> android:text="加入组" />
<Button <Button
android:id="@+id/btn_person_delete" android:id="@+id/btn_person_delete"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="48dp" android:layout_height="48dp"
android:layout_weight="1" android:layout_weight="1"
android:gravity="center" android:gravity="center"
android:text="删除成员" /> android:text="删除成员" />
<Button <Button
android:id="@+id/btn_group_delete" android:id="@+id/btn_group_delete"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="48dp" android:layout_height="48dp"
android:layout_weight="1" android:layout_weight="1"
android:gravity="center" android:gravity="center"
android:text="删除组" /> android:text="删除组" />
</LinearLayout> </LinearLayout>
</RelativeLayout> </RelativeLayout>
<RelativeLayout <RelativeLayout
android:id="@+id/group_mygroup_layout" android:id="@+id/group_mygroup_layout"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentLeft="true" android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" android:layout_alignParentStart="true"
android:layout_below="@+id/group_add_layout"> android:layout_below="@+id/group_add_layout">
<TextView <TextView
android:id="@+id/txt_group_mygroup" android:id="@+id/txt_group_mygroup"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="20dp" android:layout_height="20dp"
android:layout_marginLeft="20dp" android:layout_marginLeft="20dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:text="已创建的组" android:text="已创建的组"
android:textColor="@color/white" android:textColor="@color/white"
android:textSize="16sp" /> android:textSize="16sp" />
<View <View
android:id="@+id/line_my_group" android:id="@+id/line_my_group"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="1dip" android:layout_height="1dip"
android:layout_below="@id/txt_group_mygroup" android:layout_below="@id/txt_group_mygroup"
android:layout_margin="10dp" android:layout_margin="10dp"
android:background="#e5e5e6" /> android:background="#e5e5e6" />
</RelativeLayout> </RelativeLayout>
</RelativeLayout> </RelativeLayout>

View File

@ -7,12 +7,12 @@
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" > android:paddingRight="10dp">
<RelativeLayout <RelativeLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" > android:layout_margin="10dp">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -35,29 +35,29 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="1" android:layout_weight="1"
android:hint="@string/text_show_iat_result"
android:gravity="top|left" android:gravity="top|left"
android:hint="@string/text_show_iat_result"
android:paddingBottom="10dp" android:paddingBottom="10dp"
android:textSize="20sp" /> android:textSize="20sp" />
<EditText <EditText
android:id="@+id/iat_contacts" android:id="@+id/iat_contacts"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="1" android:layout_weight="1"
android:hint="@string/text_show_contacts"
android:gravity="top|left" android:gravity="top|left"
android:hint="@string/text_show_contacts"
android:paddingBottom="10dp" android:paddingBottom="10dp"
android:textSize="20sp" /> android:textSize="20sp" />
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/iat_recognize" android:id="@+id/iat_recognize"
@ -89,13 +89,12 @@
android:id="@+id/languageText" android:id="@+id/languageText"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="点击设置小语种,当前语种:中文(普通话)"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:textSize="20sp"
android:gravity="center_horizontal"
android:clickable="true" android:clickable="true"
android:focusable="true" android:focusable="true"
/> android:gravity="center_horizontal"
android:text="点击设置小语种,当前语种:中文(普通话)"
android:textSize="20sp" />
<Button <Button
android:id="@+id/iat_recognize_stream" android:id="@+id/iat_recognize_stream"
@ -109,32 +108,16 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:text="上传联系人、词表,可以使云端识别联系人和词表更加准确,这里上传的内容对语义理解同样有效。" android:text="上传词表,可以使云端识别更加准确,这里上传的内容对语义理解同样有效。"
android:textSize="@dimen/txt_size" /> android:textSize="@dimen/txt_size" />
<LinearLayout <Button
android:id="@+id/iat_upload_userwords"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:layout_marginBottom="4dp"
android:orientation="horizontal" > android:text="上传词表"
android:textSize="17sp" />
<Button
android:id="@+id/iat_upload_contacts"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="上传联系人"
android:textSize="17sp" />
<Button
android:id="@+id/iat_upload_userwords"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="上传词表"
android:textSize="17sp" />
</LinearLayout>
</LinearLayout> </LinearLayout>

View File

@ -1,12 +1,12 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:gravity="center_vertical"> android:gravity="center_vertical">
<ImageView <ImageView
android:id="@+id/ifly_mnotice_image_container" android:id="@+id/ifly_mnotice_image_container"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"/> android:layout_height="match_parent" />
</RelativeLayout> </RelativeLayout>

View File

@ -5,12 +5,12 @@
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" > android:paddingRight="10dp">
<RelativeLayout <RelativeLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" > android:layout_margin="10dp">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -28,32 +28,44 @@
android:background="@drawable/main_setting_btn_np" /> android:background="@drawable/main_setting_btn_np" />
</RelativeLayout> </RelativeLayout>
<EditText <ScrollView
android:id="@+id/ise_eva_text"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="120dp" android:layout_height="0dp"
android:layout_marginBottom="5dp" android:layout_weight="1">
android:gravity="top|left"
android:textSize="20sp" /> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/ise_eva_text"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_marginBottom="5dp"
android:gravity="top|left"
android:textSize="13sp" />
<TextView
android:id="@+id/ise_result_text"
android:minHeight="200dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:hint="请点击“开始评测”按钮"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>
<EditText
android:id="@+id/ise_result_text"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:editable="false"
android:gravity="top|left"
android:hint="请点击“开始评测”按钮"
android:textSize="16sp" />
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/ise_start" android:id="@+id/ise_start"
@ -75,10 +87,10 @@
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/ise_cancel" android:id="@+id/ise_cancel"

View File

@ -7,18 +7,19 @@
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" > android:paddingRight="10dp">
<RelativeLayout <RelativeLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" > android:layout_margin="10dp">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_centerInParent="true" android:layout_centerInParent="true"
android:text="讯飞语法示例" android:text="讯飞语法示例"
android:textColor="@color/black"
android:textSize="30sp" /> android:textSize="30sp" />
</RelativeLayout> </RelativeLayout>
@ -36,7 +37,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/isr_grammar" android:id="@+id/isr_grammar"
@ -54,7 +55,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/isr_recognize" android:id="@+id/isr_recognize"
@ -71,7 +72,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/isr_stop" android:id="@+id/isr_stop"

View File

@ -5,13 +5,13 @@
android:layout_marginLeft="5dp" android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" android:layout_marginRight="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" > android:orientation="vertical">
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:gravity="center" > android:gravity="center">
<TextView <TextView
android:layout_width="0dp" android:layout_width="0dp"
@ -27,7 +27,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/set_authId" android:id="@+id/set_authId"
android:maxLines="1" android:maxLines="1"
android:hint="请输入 authId"/> android:hint="请输入 authId" />
<EditText <EditText
android:id="@+id/edt_result" android:id="@+id/edt_result"
@ -43,7 +43,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/isv_getpassword" android:id="@+id/isv_getpassword"
@ -78,14 +78,14 @@
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" android:layout_marginBottom="10dp"
android:gravity="center" android:gravity="center"
android:orientation="horizontal" > android:orientation="horizontal">
<RadioGroup <RadioGroup
android:id="@+id/vocal_radioGroup1" android:id="@+id/vocal_radioGroup1"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:orientation="horizontal"
android:weightSum="2" > android:weightSum="2">
<RadioButton <RadioButton
android:id="@+id/vocal_radioEnroll" android:id="@+id/vocal_radioEnroll"
@ -93,8 +93,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1"
android:text=" 声纹注册" android:text=" 声纹注册"
android:textSize="18sp" > android:textSize="18sp"></RadioButton>
</RadioButton>
<RadioButton <RadioButton
android:id="@+id/vocal_radioVerify" android:id="@+id/vocal_radioVerify"
@ -102,8 +101,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1"
android:text=" 1:1验证" android:text=" 1:1验证"
android:textSize="18sp" > android:textSize="18sp"></RadioButton>
</RadioButton>
</RadioGroup> </RadioGroup>
</LinearLayout> </LinearLayout>
@ -111,7 +109,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/isv_reocrd" android:id="@+id/isv_reocrd"

View File

@ -5,7 +5,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:background="@android:color/transparent" android:background="@android:color/transparent"
android:orientation="vertical" android:orientation="vertical"
android:paddingBottom="3dip" > android:paddingBottom="3dip">
<TextView <TextView
android:id="@+id/group_item_content" android:id="@+id/group_item_content"
@ -13,7 +13,6 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="20dp" android:layout_marginLeft="20dp"
android:textColor="@color/white" android:textColor="@color/white"
android:textSize="20sp" > android:textSize="20sp"></TextView>
</TextView>
</LinearLayout> </LinearLayout>

View File

@ -6,7 +6,7 @@
android:background="@android:color/transparent" android:background="@android:color/transparent"
android:orientation="horizontal" android:orientation="horizontal"
android:layout_marginTop="20dp" android:layout_marginTop="20dp"
android:paddingBottom="3dip" > android:paddingBottom="3dip">
<TextView <TextView
android:id="@+id/identify_item_number" android:id="@+id/identify_item_number"
@ -15,6 +15,7 @@
android:text="第一:" android:text="第一:"
android:textColor="#ebf657" android:textColor="#ebf657"
android:textSize="20sp" /> android:textSize="20sp" />
<TextView <TextView
android:id="@+id/identify_item_user" android:id="@+id/identify_item_user"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -23,7 +24,8 @@
android:text="18505511338" android:text="18505511338"
android:textColor="#ebf657" android:textColor="#ebf657"
android:textSize="20sp" /> android:textSize="20sp" />
<TextView
<TextView
android:id="@+id/identify_item_score" android:id="@+id/identify_item_score"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"

View File

@ -4,15 +4,7 @@
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@drawable/list_bg_color" android:background="@drawable/list_bg_color"
android:descendantFocusability="blocksDescendants" android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" > android:orientation="horizontal">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_"
android:layout_marginRight="@dimen/margin_"
android:layout_marginTop="@dimen/pading_"
android:textSize="@dimen/btn_size" />
</LinearLayout> </LinearLayout>

View File

@ -3,28 +3,101 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@drawable/layout_backgroud" android:background="@drawable/layout_backgroud"
android:orientation="vertical" > android:orientation="vertical">
<include layout="@layout/title" /> <include layout="@layout/title" />
<TextView <TextView
android:id="@+id/edit_text" android:id="@+id/tip"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_" android:layout_marginLeft="@dimen/margin_"
android:layout_marginRight="@dimen/margin_" android:layout_marginRight="@dimen/margin_"
android:textColor="@color/white"
android:textSize="@dimen/txt_size" /> android:textSize="@dimen/txt_size" />
<ListView <ScrollView
android:id="@+id/listview_main"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="0dp"
android:layout_marginTop="10dp" android:layout_marginTop="20dp"
android:layout_marginLeft="5dp" android:layout_weight="1">
android:layout_marginRight="5dp"
android:cacheColorHint="@color/white" <LinearLayout
android:divider="@drawable/line_background" android:layout_width="match_parent"
android:dividerHeight="@dimen/line_height" android:layout_height="wrap_content"
android:paddingBottom="5dp" /> android:orientation="vertical">
<Button
android:id="@+id/iatBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验语音听写"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
<Button
android:id="@+id/asrBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验语法识别"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
<Button
android:id="@+id/nlpBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验语义理解"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
<Button
android:id="@+id/ttsBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验语音合成"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
<Button
android:id="@+id/iseBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验语音评测"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
<Button
android:id="@+id/faceBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:text="立刻体验人脸识别"
android:textColor="@color/black"
android:textSize="@dimen/btn_size" />
</LinearLayout>
</ScrollView>
</LinearLayout> </LinearLayout>

View File

@ -6,7 +6,7 @@
android:focusableInTouchMode="true" android:focusableInTouchMode="true"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:padding="10dp" > android:padding="10dp">
<TextView <TextView
android:layout_width="match_parent" android:layout_width="match_parent"
@ -21,7 +21,7 @@
android:layout_height="0dp" android:layout_height="0dp"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:layout_weight="1" android:layout_weight="1"
android:gravity="center" > android:gravity="center">
<ImageView <ImageView
android:id="@+id/online_img" android:id="@+id/online_img"
@ -37,7 +37,7 @@
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<EditText <EditText
android:id="@+id/online_authid" android:id="@+id/online_authid"
@ -46,20 +46,19 @@
android:digits="abcdefghijklmnopqrstuvwxyz0123456789_" android:digits="abcdefghijklmnopqrstuvwxyz0123456789_"
android:hint="请输入 authid" android:hint="请输入 authid"
android:maxLength="18" android:maxLength="18"
android:textSize="16sp" > android:textSize="16sp">
<requestFocus /> <requestFocus />
</EditText> </EditText>
</LinearLayout> </LinearLayout>
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/online_pick" android:id="@+id/online_pick"
@ -83,7 +82,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/online_reg" android:id="@+id/online_reg"
@ -108,7 +107,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/btn_modle_delete" android:id="@+id/btn_modle_delete"
@ -116,7 +115,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1"
android:textSize="20sp" android:textSize="20sp"
android:text="@string/face_model_delete"/> android:text="@string/face_model_delete" />
<Button <Button
android:id="@+id/btn_identity" android:id="@+id/btn_identity"

View File

@ -3,13 +3,14 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="top" android:layout_gravity="top"
android:gravity="center" > android:gravity="center">
<TextView <TextView
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" android:layout_margin="10dp"
android:gravity="center" android:gravity="center"
android:textColor="@color/white"
android:text="讯飞语音示例" android:text="讯飞语音示例"
android:textSize="30sp" /> android:textSize="30sp" />

View File

@ -7,12 +7,12 @@
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" > android:paddingRight="10dp">
<RelativeLayout <RelativeLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" > android:layout_margin="10dp">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -44,14 +44,14 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="5dp" android:layout_marginBottom="5dp"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:orientation="horizontal" > android:orientation="horizontal">
<RadioGroup <RadioGroup
android:id="@+id/tts_rediogroup" android:id="@+id/tts_rediogroup"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="2" android:layout_weight="2"
android:orientation="horizontal" > android:orientation="horizontal">
<RadioButton <RadioButton
android:id="@+id/tts_radioCloud" android:id="@+id/tts_radioCloud"
@ -77,7 +77,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/tts_play" android:id="@+id/tts_play"
@ -102,7 +102,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/tts_pause" android:id="@+id/tts_pause"

View File

@ -7,12 +7,12 @@
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingRight="10dp" > android:paddingRight="10dp">
<RelativeLayout <RelativeLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_margin="10dp" > android:layout_margin="10dp">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
@ -46,7 +46,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/text_understander" android:id="@+id/text_understander"
@ -71,7 +71,7 @@
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:gravity="center_horizontal" android:gravity="center_horizontal"
android:orientation="horizontal" > android:orientation="horizontal">
<Button <Button
android:id="@+id/understander_stop" android:id="@+id/understander_stop"

View File

@ -8,6 +8,7 @@
<drawable name="line_background">#161823</drawable> <drawable name="line_background">#161823</drawable>
<color name="white">#FFFFFF</color> <color name="white">#FFFFFF</color>
<color name="black">#000</color>
<!-- 控件按下时显示的颜色 --> <!-- 控件按下时显示的颜色 -->
<color name="list_backgroud_color">#2fb3cb</color> <color name="list_backgroud_color">#2fb3cb</color>

File diff suppressed because one or more lines are too long

View File

@ -1,15 +1,16 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<style name="dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item> <style name="dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowIsFloating">true</item> <item name="android:windowFrame">@null</item>
<item name="android:windowIsTranslucent">true</item> <item name="android:windowIsFloating">true</item>
<item name="android:windowNoTitle">true</item> <item name="android:windowIsTranslucent">true</item>
<item name="android:background">@android:color/transparent</item> <item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item> <item name="android:background">@android:color/transparent</item>
<item name="android:backgroundDimEnabled">true</item> <item name="android:windowBackground">@android:color/transparent</item>
<item name="android:backgroundDimAmount">0.6</item> <item name="android:backgroundDimEnabled">true</item>
</style> <item name="android:backgroundDimAmount">0.6</item>
</style>
<style name="textStyle"> <style name="textStyle">
<item name="android:textSize">16sp</item> <item name="android:textSize">16sp</item>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference <ListPreference
android:key="iat_language_preference" android:key="iat_language_preference"
@ -7,21 +7,21 @@
android:entries="@array/language_entries" android:entries="@array/language_entries"
android:entryValues="@array/language_values" android:entryValues="@array/language_values"
android:summary="支持:普通话,粤语,英语 " android:summary="支持:普通话,粤语,英语 "
android:defaultValue="mandarin" /> android:defaultValue="mandarin" />
<EditTextPreference <EditTextPreference
android:key="iat_vadbos_preference" android:key="iat_vadbos_preference"
android:title="前端点超时" android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms" android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写5000其他4000" android:summary="默认值短信转写5000其他4000"
android:defaultValue="5000" /> android:defaultValue="5000" />
<EditTextPreference <EditTextPreference
android:key="iat_vadeos_preference" android:key="iat_vadeos_preference"
android:title="后端点超时" android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms" android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写1800其他700 " android:summary="默认值短信转写1800其他700 "
android:defaultValue="1800" /> android:defaultValue="1800" />
<ListPreference <ListPreference
android:key="iat_punc_preference" android:key="iat_punc_preference"
@ -29,11 +29,11 @@
android:entries="@array/punc_entries" android:entries="@array/punc_entries"
android:entryValues="@array/punc_values" android:entryValues="@array/punc_values"
android:summary="默认值:有标点 " android:summary="默认值:有标点 "
android:defaultValue="1" /> android:defaultValue="1" />
<CheckBoxPreference <CheckBoxPreference
android:key="@string/pref_key_iat_show" android:key="@string/pref_key_iat_show"
android:title="@string/pref_title_iat_show" android:title="@string/pref_title_iat_show"
android:defaultValue="true" /> android:defaultValue="true" />
</PreferenceScreen> </PreferenceScreen>

View File

@ -37,7 +37,7 @@
android:summary="" android:summary=""
android:defaultValue="1800"/> android:defaultValue="1800"/>
<EditTextPreference <EditTextPreference
android:key="speech_timeout" android:key="speech_timeout"
android:title="评测超时" android:title="评测超时"
android:summary="" android:summary=""

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference <EditTextPreference
android:dialogTitle="请输入语速:在线(0-100)本地(0-200)" android:dialogTitle="请输入语速:在线(0-100)本地(0-200)"

View File

@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference <ListPreference
android:key="understander_language_preference" android:key="understander_language_preference"
android:title="语言设置" android:title="语言设置"
android:entries="@array/language_entries" android:entries="@array/language_entries"
android:entryValues="@array/language_values" android:entryValues="@array/language_values"
android:summary="支持:普通话,粤语,英语 " android:summary="支持:普通话,粤语,英语 "
android:defaultValue="mandarin" /> android:defaultValue="mandarin" />
<EditTextPreference <EditTextPreference
android:key="understander_vadbos_preference" android:key="understander_vadbos_preference"
android:title="前端点超时" android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms" android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写5000其他4000" android:summary="默认值短信转写5000其他4000"
android:defaultValue="4000" /> android:defaultValue="4000" />
<EditTextPreference <EditTextPreference
android:key="understander_vadeos_preference" android:key="understander_vadeos_preference"
android:title="后端点超时" android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms" android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写1800其他700 " android:summary="默认值短信转写1800其他700 "
android:defaultValue="700" /> android:defaultValue="700" />
<ListPreference <ListPreference
android:key="understander_punc_preference" android:key="understander_punc_preference"
@ -27,13 +27,13 @@
android:entries="@array/punc_entries" android:entries="@array/punc_entries"
android:entryValues="@array/punc_values" android:entryValues="@array/punc_values"
android:summary="默认值:有标点 " android:summary="默认值:有标点 "
android:defaultValue="1" /> android:defaultValue="1" />
<!-- <CheckBoxPreference --> <!-- <CheckBoxPreference -->
<!-- android:key="nbest_preference" --> <!-- android:key="nbest_preference" -->
<!-- android:title="@string/set_multiple_candidate_title" --> <!-- android:title="@string/set_multiple_candidate_title" -->
<!-- android:summary="@string/set_multiple_candidate_summary" --> <!-- android:summary="@string/set_multiple_candidate_summary" -->
<!-- android:defaultValue="false" /> --> <!-- android:defaultValue="false" /> -->
</PreferenceScreen> </PreferenceScreen>

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference <ListPreference
android:key="url_preference" android:key="url_preference"
android:title="域名设置" android:title="域名设置"
android:entries="@array/machine_entries" android:entries="@array/machine_entries"
android:entryValues="@array/machine_values" android:entryValues="@array/machine_values"
android:summary="支持:鲁谷,广州,森华 " /> android:summary="支持:鲁谷,广州,森华 " />
<EditTextPreference <EditTextPreference
android:key="url_edit" android:key="url_edit"
android:title="输入域名(优先级较高) 格式参考:域名(+:端口)" android:title="输入域名(优先级较高) 格式参考:域名(+:端口)"
android:summary=""/> android:summary="" />
</PreferenceScreen> </PreferenceScreen>

Binary file not shown.