滨化讯飞插件

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

View File

@ -1,3 +1,2 @@
<?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"
package="com.iflytek.voicedemo"
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
android:icon="@drawable/icon"
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
android:name="com.iflytek.voicedemo.MainActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:icon="@drawable/icon"
android:label="讯飞语音示例"
android:screenOrientation="portrait" >
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.iflytek.speech.setting.TtsSettings" >
</activity>
<activity android:name="com.iflytek.speech.setting.IatSettings" >
</activity>
<activity android:name="com.iflytek.speech.setting.TtsSettings" />
<activity android:name="com.iflytek.speech.setting.IatSettings" />
<activity
android:name="com.iflytek.voicedemo.IatDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.AsrDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.TtsDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.IseDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
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>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.faceonline.OnlineFaceDemo"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.IdentifyGroup.GroupManagerActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait">
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.IdentifyGroup.FaceIdentifyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
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>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.voicedemo.IdentifyGroup.ResultIdentifyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait">
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.speech.setting.IseSettings"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<activity
android:name="com.iflytek.speech.setting.UrlSettings"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale"
android:screenOrientation="portrait" >
</activity>
android:screenOrientation="portrait" />
<!-- 移动统计分析 -->
<meta-data
android:name="IFLYTEK_APPKEY"
@ -95,20 +88,4 @@
</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>

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package com.iflytek.ise.result;
@ -11,13 +11,13 @@ package com.iflytek.ise.result;
* @date 2015年1月14日 上午11:12:58
*/
public class FinalResult extends Result {
public int ret;
public float total_score;
@Override
public String toString() {
return "返回值:" + ret + ",总分:" + total_score;
}
public int ret;
public float total_score;
@Override
public String toString() {
return "返回值:" + ret + ",总分:" + total_score;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package com.iflytek.ise.result.util;
@ -13,28 +13,28 @@ import java.util.HashMap;
* @date 2015年1月13日 下午6:05:03
*/
public class ResultTranslateUtil {
private static HashMap<Integer, String> dp_message_map = new HashMap<Integer, String>();
private static HashMap<String, String> special_content_map = new HashMap<String, String>();
static {
dp_message_map.put(0, "正常");
dp_message_map.put(16, "漏读");
dp_message_map.put(32, "增读");
dp_message_map.put(64, "回读");
dp_message_map.put(128, "替换");
special_content_map.put("sil", "静音");
special_content_map.put("silv", "静音");
special_content_map.put("fil", "噪音");
}
public static String getDpMessageInfo(int dp_message) {
return dp_message_map.get(dp_message);
}
public static String getContent(String content) {
String val = special_content_map.get(content);
return (null == val)? content: val;
}
private static HashMap<Integer, String> dp_message_map = new HashMap<Integer, String>();
private static HashMap<String, String> special_content_map = new HashMap<String, String>();
static {
dp_message_map.put(0, "正常");
dp_message_map.put(16, "漏读");
dp_message_map.put(32, "增读");
dp_message_map.put(64, "回读");
dp_message_map.put(128, "替换");
special_content_map.put("sil", "静音");
special_content_map.put("silv", "静音");
special_content_map.put("fil", "噪音");
}
public static String getDpMessageInfo(int dp_message) {
return dp_message_map.get(dp_message);
}
public static String getContent(String content) {
String val = special_content_map.get(content);
return (null == val) ? content : val;
}
}

View File

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

View File

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

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package com.iflytek.speech.setting;
@ -7,8 +7,8 @@ import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Window;
@ -17,185 +17,227 @@ import android.widget.Toast;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.voicedemo.R;
import java.util.HashMap;
/**
* 评测设置界面
*/
public class IseSettings extends PreferenceActivity {
private final static String PREFER_NAME = "ise_settings";
private ListPreference mLanguagePref;
private ListPreference mCategoryPref;
private ListPreference mResultLevelPref;
private EditTextPreference mVadBosPref;
private EditTextPreference mVadEosPref;
private EditTextPreference mSpeechTimeoutPref;
private Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
addPreferencesFromResource(R.xml.ise_settings);
initUI();
}
private final static String PREFER_NAME = "ise_settings";
private void initUI() {
mLanguagePref = (ListPreference) findPreference(SpeechConstant.LANGUAGE);
mCategoryPref = (ListPreference) findPreference(SpeechConstant.ISE_CATEGORY);
mResultLevelPref = (ListPreference) findPreference(SpeechConstant.RESULT_LEVEL);
mVadBosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_BOS);
mVadEosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_EOS);
mSpeechTimeoutPref = (EditTextPreference) findPreference(SpeechConstant.KEY_SPEECH_TIMEOUT);
private ListPreference mLanguagePref;
private ListPreference mCategoryPref;
private ListPreference mResultLevelPref;
private EditTextPreference mVadBosPref;
private EditTextPreference mVadEosPref;
private EditTextPreference mSpeechTimeoutPref;
mToast = Toast.makeText(IseSettings.this, "", Toast.LENGTH_LONG);
mLanguagePref.setSummary("当前:" + mLanguagePref.getEntry());
mCategoryPref.setSummary("当前:" + mCategoryPref.getEntry());
mResultLevelPref.setSummary("当前:" + mResultLevelPref.getEntry());
mVadBosPref.setSummary("当前:" + mVadBosPref.getText() + "ms");
mVadEosPref.setSummary("当前:" + mVadEosPref.getText() + "ms");
String speech_timeout = mSpeechTimeoutPref.getText();
String summary = "当前:" + speech_timeout;
if (!"-1".equals(speech_timeout)) {
summary += "ms";
}
mSpeechTimeoutPref.setSummary(summary);
mLanguagePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ("zh_cn".equals(newValue.toString())) {
if ("plain".equals(mResultLevelPref.getValue())) {
showTip("汉语评测结果格式不支持plain设置");
return false;
}
} else {
if ("read_syllable".equals(mCategoryPref.getValue())) {
showTip("英语评测不支持单字");
return false;
}
}
int newValueIndex = mLanguagePref.findIndexOfValue(newValue.toString());
String newEntry = (String) mLanguagePref.getEntries()[newValueIndex];
mLanguagePref.setSummary("当前:" + newEntry);
return true;
}
});
mCategoryPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
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());
String newEntry = (String) mCategoryPref.getEntries()[newValueIndex];
mCategoryPref.setSummary("当前:" + newEntry);
return true;
}
});
mResultLevelPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
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());
return true;
}
});
mVadBosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
mVadBosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
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;
}
mVadBosPref.setSummary("当前:" + bos + "ms");
return true;
}
});
mVadEosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
mVadEosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
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");
return true;
}
});
mSpeechTimeoutPref.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED|InputType.TYPE_CLASS_NUMBER);
mSpeechTimeoutPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@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.setText(str);
mToast.show();
}
}
private Toast mToast;
private HashMap<String, String> zhMap = new HashMap<>();
private HashMap<String, String> enMap = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
addPreferencesFromResource(R.xml.ise_settings);
initCategoryMap();
initUI();
}
private void initCategoryMap() {
zhMap.put("read_syllable", "单字");
zhMap.put("read_word", "词语");
zhMap.put("read_sentence", "句子");
zhMap.put("read_chapter", "篇章");
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", "英文口头翻译");
}
private void initUI() {
mLanguagePref = (ListPreference) findPreference(SpeechConstant.LANGUAGE);
mCategoryPref = (ListPreference) findPreference(SpeechConstant.ISE_CATEGORY);
mResultLevelPref = (ListPreference) findPreference(SpeechConstant.RESULT_LEVEL);
mVadBosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_BOS);
mVadEosPref = (EditTextPreference) findPreference(SpeechConstant.VAD_EOS);
mSpeechTimeoutPref = (EditTextPreference) findPreference(SpeechConstant.KEY_SPEECH_TIMEOUT);
mToast = Toast.makeText(IseSettings.this, "", Toast.LENGTH_LONG);
mLanguagePref.setSummary("当前:" + mLanguagePref.getEntry());
mCategoryPref.setSummary("当前:" + mCategoryPref.getEntry());
mResultLevelPref.setSummary("当前:" + mResultLevelPref.getEntry());
mVadBosPref.setSummary("当前:" + mVadBosPref.getText() + "ms");
mVadEosPref.setSummary("当前:" + mVadEosPref.getText() + "ms");
String speech_timeout = mSpeechTimeoutPref.getText();
String summary = "当前:" + speech_timeout;
if (!"-1".equals(speech_timeout)) {
summary += "ms";
}
mSpeechTimeoutPref.setSummary(summary);
mLanguagePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String categoryValue = mCategoryPref.getValue();
if ("zh_cn".equals(newValue.toString())) {
// 中文
if ("plain".equals(mResultLevelPref.getValue())) {
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;
}
}
int newValueIndex = mLanguagePref.findIndexOfValue(newValue.toString());
String newEntry = (String) mLanguagePref.getEntries()[newValueIndex];
mLanguagePref.setSummary("当前:" + newEntry);
return true;
}
});
mCategoryPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String categoryValue = newValue.toString();
if ("en_us".equals(mLanguagePref.getValue())) {
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;
}
}
int newValueIndex = mCategoryPref.findIndexOfValue(newValue.toString());
String newEntry = (String) mCategoryPref.getEntries()[newValueIndex];
mCategoryPref.setSummary("当前:" + newEntry);
return true;
}
});
mResultLevelPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
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());
return true;
}
});
mVadBosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
mVadBosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
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;
}
mVadBosPref.setSummary("当前:" + bos + "ms");
return true;
}
});
mVadEosPref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
mVadEosPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
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");
return true;
}
});
mSpeechTimeoutPref.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_CLASS_NUMBER);
mSpeechTimeoutPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@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

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

View File

@ -1,18 +1,15 @@
package com.iflytek.speech.setting;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.support.annotation.Nullable;
import android.view.Window;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.voicedemo.R;
import androidx.annotation.Nullable;
import java.util.List;
import com.iflytek.voicedemo.R;
/**
* @author hjyu
@ -33,7 +30,7 @@ public class UrlSettings extends PreferenceActivity implements Preference.OnPref
getPreferenceManager().setSharedPreferencesName(PREFER_NAME);
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.setOnPreferenceChangeListener(this);

View File

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

View File

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

View File

@ -1,144 +1,144 @@
package com.iflytek.speech.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
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 {
/**
* 读取asset目录下文件
* @return content
*/
public static String readFile(Context mContext,String file,String code)
{
int len = 0;
byte []buf = null;
String result = "";
try {
InputStream in = mContext.getAssets().open(file);
len = in.available();
buf = new byte[len];
in.read(buf, 0, len);
result = new String(buf,code);
} catch (Exception e) {
e.printStackTrace();
}
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 {
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 "";
}
/**
* 读取asset目录下音频文件
*
* @return 二进制文件数据
*/
public static byte[] readAudioFile(Context context, String filename) {
try {
InputStream ins = context.getAssets().open(filename);
byte[] data = new byte[ins.available()];
ins.read(data);
ins.close();
return data;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 读取asset目录下文件
*
* @return content
*/
public static String readFile(Context mContext, String file, String code) {
int len = 0;
byte[] buf = null;
String result = "";
try {
InputStream in = mContext.getAssets().open(file);
len = in.available();
buf = new byte[len];
in.read(buf, 0, len);
result = new String(buf, code);
} catch (Exception e) {
e.printStackTrace();
}
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 {
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 "";
}
/**
* 读取asset目录下音频文件
*
* @return 二进制文件数据
*/
public static byte[] readAudioFile(Context context, String filename) {
try {
InputStream ins = context.getAssets().open(filename);
byte[] data = new byte[ins.available()];
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.JSONTokener;
import android.util.Log;
/**
* Json结果解析类
*/
public class JsonParser {
public static String parseIatResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
public static String parseIatResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
// 转写结果词默认使用第一个结果
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w"));
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
// 转写结果词默认使用第一个结果
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w"));
// 如果需要多候选结果解析数组其他字段
// for(int j = 0; j < items.length(); j++)
// {
// JSONObject obj = items.getJSONObject(j);
// ret.append(obj.getString("w"));
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
public static String parseGrammarResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
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"));
ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
public static String parseLocalGrammarResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
public static String parseGrammarResult(String json, String engType) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
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"));
ret.append("\n");
}
}
ret.append("【置信度】" + joResult.optInt("sc"));
JSONArray words = joResult.getJSONArray("ws");
// 云端和本地结果分情况解析
if ("cloud".equals(engType)) {
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
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"));
ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n");
}
}
} else if ("local".equals(engType)) {
ret.append("【结果】");
for (int i = 0; i < words.length(); i++) {
JSONObject wsItem = words.getJSONObject(i);
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");
}
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
} 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));
public static String parseGrammarResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
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"));
ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
public static String parseLocalGrammarResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
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"));
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");
for (int i = 0; i < words.length(); i++) {
JSONObject obj = words.getJSONObject(i);
ret.append(obj.getString(key));
}*/
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
}

View File

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

View File

@ -1,57 +1,55 @@
package com.iflytek.speech.util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Xml结果解析类
*/
public class XmlParser {
public static String parseNluResult(String xml)
{
StringBuffer buffer = new StringBuffer();
try
{
// DOM builder
DocumentBuilder domBuilder = null;
// DOM doc
Document domDoc = null;
public static String parseNluResult(String xml) {
StringBuffer buffer = new StringBuffer();
try {
// DOM builder
DocumentBuilder domBuilder = null;
// DOM doc
Document domDoc = null;
// init DOM
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
domBuilder = domFact.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes());
domDoc = domBuilder.parse(is);
// init DOM
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
domBuilder = domFact.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes());
domDoc = domBuilder.parse(is);
// 获取根节点
Element root = (Element) domDoc.getDocumentElement();
Element raw = (Element)root.getElementsByTagName("rawtext").item(0);
buffer.append("【识别结果】" + raw.getFirstChild().getNodeValue());
buffer.append("\n");
Element e = (Element)root.getElementsByTagName("result").item(0);
Element focus = (Element)e.getElementsByTagName("focus").item(0);
buffer.append("【FOCUS】" + focus.getFirstChild().getNodeValue());
buffer.append("\n");
Element action = (Element)e.getElementsByTagName("action").item(0);
Element operation = (Element)action.getElementsByTagName("operation").item(0);
buffer.append("【ACTION】" + operation.getFirstChild().getNodeValue());
buffer.append("\n");
// 获取根节点
Element root = (Element) domDoc.getDocumentElement();
}catch(Exception e){
e.printStackTrace();
};
buffer.append("【ALL】" + xml);
return buffer.toString();
}
Element raw = (Element) root.getElementsByTagName("rawtext").item(0);
buffer.append("【识别结果】" + raw.getFirstChild().getNodeValue());
buffer.append("\n");
Element e = (Element) root.getElementsByTagName("result").item(0);
Element focus = (Element) e.getElementsByTagName("focus").item(0);
buffer.append("【FOCUS】" + focus.getFirstChild().getNodeValue());
buffer.append("\n");
Element action = (Element) e.getElementsByTagName("action").item(0);
Element operation = (Element) action.getElementsByTagName("operation").item(0);
buffer.append("【ACTION】" + operation.getFirstChild().getNodeValue());
buffer.append("\n");
} catch (Exception e) {
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.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.GrammarListener;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.LexiconListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
@ -27,285 +23,251 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.speech.util.FucUtil;
import com.iflytek.speech.util.JsonParser;
/*import com.iflytek.sunflower.FlowerCollector;*/
/**
* 识别示例
*/
public class AsrDemo extends Activity implements OnClickListener{
private static String TAG = AsrDemo.class.getSimpleName();
// 语音识别对象
private SpeechRecognizer mAsr;
private Toast mToast;
// 缓存
private SharedPreferences mSharedPreferences;
// 云端语法文件
private String mCloudGrammar = null;
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_BNF = "bnf";
public class AsrDemo extends Activity implements OnClickListener {
private static String TAG = AsrDemo.class.getSimpleName();
// 语音识别对象
private SpeechRecognizer mAsr;
private Toast mToast;
// 缓存
private SharedPreferences mSharedPreferences;
// 云端语法文件
private String mCloudGrammar = null;
private String mEngineType = SpeechConstant.TYPE_CLOUD;
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_BNF = "bnf";
@SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isrdemo);
initLayout();
// 初始化识别对象
mAsr = SpeechRecognizer.createRecognizer(AsrDemo.this, mInitListener);
mCloudGrammar = FucUtil.readFile(this,"grammar_sample.abnf","utf-8");
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);
private String mEngineType = SpeechConstant.TYPE_CLOUD;
@SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isrdemo);
initLayout();
// 初始化识别对象
mAsr = SpeechRecognizer.createRecognizer(AsrDemo.this, mInitListener);
mCloudGrammar = FucUtil.readFile(this, "grammar_sample.abnf", "utf-8");
mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
}
/**
* 初始化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;
// 函数调用返回值
private int ret = 0;
}
// 语法词典临时变量
String mContent;
// 函数调用返回值
int ret = 0;
@Override
public void onClick(View view) {
if( null == mAsr ){
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" );
return;
}
if(null == mEngineType) {
showTip("请先选择识别引擎类型");
return;
}
switch(view.getId())
{
case R.id.isr_grammar:
showTip("上传预设关键词/语法文件");
// 在线-构建语法文件生成语法id
((EditText)findViewById(R.id.isr_text)).setText(mCloudGrammar);
mContent = new String(mCloudGrammar);
//指定引擎类型
mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
mAsr.setParameter(SpeechConstant.TEXT_ENCODING,"utf-8");
ret = mAsr.buildGrammar(GRAMMAR_TYPE_ABNF, mContent, mCloudGrammarListener);
if(ret != ErrorCode.SUCCESS)
showTip("语法构建失败,错误码:" + ret+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
public void onClick(View view) {
if (null == mAsr) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return;
}
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;
}
}
/**
if (null == mEngineType) {
showTip("请先选择识别引擎类型");
return;
}
switch (view.getId()) {
case R.id.isr_grammar:
showTip("上传预设关键词/语法文件");
// 在线-构建语法文件生成语法id
((EditText) findViewById(R.id.isr_text)).setText(mCloudGrammar);
mContent = new String(mCloudGrammar);
//指定引擎类型
mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
ret = mAsr.buildGrammar(GRAMMAR_TYPE_ABNF, mContent, mCloudGrammarListener);
if (ret != ErrorCode.SUCCESS) {
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;
}
}
/**
* 初始化监听器
*/
private InitListener mInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d(TAG, "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:"+code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
@Override
public void onInit(int code) {
Log.d(TAG, "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
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() {
@Override
public void onBuildFinish(String grammarId, SpeechError error) {
if(error == null){
String grammarID = new String(grammarId);
Editor editor = mSharedPreferences.edit();
if(!TextUtils.isEmpty(grammarId))
editor.putString(KEY_GRAMMAR_ABNF_ID, grammarID);
editor.commit();
showTip("语法构建成功:" + grammarId);
}else{
showTip("语法构建失败,错误码:" + error.getErrorCode()+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
private GrammarListener mCloudGrammarListener = new GrammarListener() {
@Override
public void onBuildFinish(String grammarId, SpeechError error) {
if (error == null) {
String grammarID = new String(grammarId);
Editor editor = mSharedPreferences.edit();
if (!TextUtils.isEmpty(grammarId))
editor.putString(KEY_GRAMMAR_ABNF_ID, grammarID);
editor.commit();
showTip("语法构建成功:" + grammarId);
} else {
showTip("语法构建失败,错误码:" + error.getErrorCode() + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
/**
/**
* 识别监听器
*/
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
Log.d(TAG, "返回音频数据:"+data.length);
showTip("当前正在说话,音量大小:" + volume);
Log.d(TAG, "返回音频数据:" + data.length);
}
@Override
public void onResult(final RecognizerResult result, boolean isLast) {
if (null != result) {
Log.d(TAG, "recognizer result" + result.getResultString());
String text ;
if("cloud".equalsIgnoreCase(mEngineType)){
text = JsonParser.parseGrammarResult(result.getResultString());
}else {
text = JsonParser.parseLocalGrammarResult(result.getResultString());
}
// 显示
((EditText)findViewById(R.id.isr_text)).setText(text);
} else {
Log.d(TAG, "recognizer result : null");
}
if (null != result) {
Log.d(TAG, "recognizer result" + result.getResultString());
String text;
if ("cloud".equalsIgnoreCase(mEngineType)) {
text = JsonParser.parseGrammarResult(result.getResultString());
} else {
text = JsonParser.parseLocalGrammarResult(result.getResultString());
}
// 显示
((EditText) findViewById(R.id.isr_text)).setText(text);
} else {
Log.d(TAG, "recognizer result : null");
}
}
@Override
public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话");
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话");
}
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话");
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
showTip("onError Code" + error.getErrorCode());
}
@Override
public void onError(SpeechError error) {
showTip("onError Code" + error.getErrorCode());
}
@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);
// }
}
@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);
// }
}
};
private void showTip(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mToast.setText(str);
mToast.show();
}
});
}
/**
* 参数设置
* @return
*/
public boolean setParam(){
boolean result = false;
//设置识别引擎
mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
//设置返回结果为json格式
mAsr.setParameter(SpeechConstant.RESULT_TYPE, "json");
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();
}
});
}
if("cloud".equalsIgnoreCase(mEngineType))
{
String grammarId = mSharedPreferences.getString(KEY_GRAMMAR_ABNF_ID, null);
if(TextUtils.isEmpty(grammarId))
{
result = false;
}else {
//设置云端识别使用的语法id
mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
result = true;
}
}
/**
* 参数设置
*
* @return
*/
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);
if (TextUtils.isEmpty(grammarId)) {
result = false;
} else {
//设置云端识别使用的语法id
mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
result = true;
}
}
// 设置音频保存路径保存音频格式支持pcmwav
mAsr.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/asr.wav");
return result;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != mAsr) {
// 退出时释放连接
mAsr.cancel();
mAsr.destroy();
}
}
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
mAsr.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/asr.wav");
return result;
}
@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;
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.app.Activity;
import android.app.AlertDialog;
@ -14,10 +7,6 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.view.View;
import android.view.View.OnClickListener;
@ -36,489 +25,404 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
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.util.FucUtil;
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 {
private static String TAG = IatDemo.class.getSimpleName();
// 语音听写对象
private SpeechRecognizer mIat;
// 语音听写UI
private RecognizerDialog mIatDialog;
// 用HashMap存储听写结果
private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
private static String TAG = IatDemo.class.getSimpleName();
// 语音听写对象
private SpeechRecognizer mIat;
// 语音听写UI
private RecognizerDialog mIatDialog;
// 用HashMap存储听写结果
private HashMap<String, String> mIatResults = new LinkedHashMap<>();
private EditText mResultText;
private EditText showContacts;
private TextView languageText;
private Toast mToast;
private SharedPreferences mSharedPreferences;
// 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD;
private EditText mResultText;
private EditText showContacts;
private TextView languageText;
private Toast mToast;
private SharedPreferences mSharedPreferences;
// 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD;
private String[] languageEntries ;
private String[] languageValues;
private String language="zh_cn";
private int selectedNum=0;
private String[] languageEntries;
private String[] languageValues;
private String language = "zh_cn";
private int selectedNum = 0;
private String resultType = "json";
private String resultType = "json";
private boolean cyclic = false;//音频流识别是否循环调用
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);
}
private StringBuffer buffer = new StringBuffer();
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
*/
private void initLayout() {
findViewById(R.id.iat_recognize).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_stop).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_cancel).setOnClickListener(IatDemo.this);
findViewById(R.id.image_iat_set).setOnClickListener(IatDemo.this);
findViewById(R.id.languageText).setOnClickListener(IatDemo.this);
}
/**
* 初始化Layout
*/
private void initLayout() {
findViewById(R.id.iat_recognize).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_recognize_stream).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_upload_userwords).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_stop).setOnClickListener(IatDemo.this);
findViewById(R.id.iat_cancel).setOnClickListener(IatDemo.this);
findViewById(R.id.image_iat_set).setOnClickListener(IatDemo.this);
findViewById(R.id.languageText).setOnClickListener(IatDemo.this);
}
int ret = 0; // 函数调用返回值
int ret = 0; // 函数调用返回值
@Override
public void onClick(View view) {
if( null == mIat ){
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" );
return;
}
switch (view.getId()) {
// 进入参数设置页面
case R.id.image_iat_set:
Intent intents = new Intent(IatDemo.this, IatSettings.class);
startActivity(intents);
break;
// 开始听写
// 如何判断一次听写结束OnResult isLast=true 或者 onError
case R.id.iat_recognize:
// 移动数据分析收集开始听写事件
// FlowerCollector.onEvent(IatDemo.this, "iat_recognize");
@Override
public void onClick(View view) {
if (null == mIat) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return;
}
buffer.setLength(0);
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_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);
switch (view.getId()) {
// 进入参数设置页面
case R.id.image_iat_set:
Intent intents = new Intent(IatDemo.this, IatSettings.class);
startActivity(intents);
break;
// 开始听写
// 如何判断一次听写结束OnResult isLast=true 或者 onError
case R.id.iat_recognize:
buffer.setLength(0);
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;
}
}
// 指定引擎类型
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;
}
}
/**
* 初始化监听器
*/
private InitListener mInitListener = new InitListener() {
/**
* 初始化监听器
*/
private InitListener mInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d(TAG, "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
@Override
public void onInit(int code) {
Log.d(TAG, "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
}
};
/**
* 在线听写支持多种小语种设置支持语言类型如下
* <item>zh_cn</item> 中文
* <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);
}
/**
* 在线听写支持多种小语种设置支持语言类型如下
* <item>zh_cn</item> 中文
* <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);
}
/**
* 上传联系人/词表监听器
*/
private LexiconListener mLexiconListener = new LexiconListener() {
/**
* 上传联系人/词表监听器
*/
private LexiconListener mLexiconListener = new LexiconListener() {
@Override
public void onLexiconUpdated(String lexiconId, SpeechError error) {
if (error != null) {
showTip(error.toString());
} else {
showTip(getString(R.string.text_upload_success));
}
}
};
@Override
public void onLexiconUpdated(String lexiconId, SpeechError error) {
if (error != null) {
showTip(error.toString());
} else {
showTip(getString(R.string.text_upload_success));
}
}
};
/**
* 听写监听器
*/
private RecognizerListener mRecognizerListener = new RecognizerListener() {
/**
* 听写监听器
*/
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// Tips
// 错误码10118(您没有说话)可能是录音机权限被禁需要提示用户打开应用的录音权限
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// Tips
// 错误码10118(您没有说话)可能是录音机权限被禁需要提示用户打开应用的录音权限
Log.d(TAG, "onError " + error.getPlainDescription(true));
showTip(error.getPlainDescription(true));
}
}
@Override
public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话");
}
@Override
public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
showTip("结束说话");
}
@Override
public void onResult(RecognizerResult results, boolean isLast) {
Log.d(TAG, results.getResultString());
System.out.println(flg++);
if (resultType.equals("json")) {
@Override
public void onResult(RecognizerResult results, boolean isLast) {
Log.d(TAG, results.getResultString());
if (isLast) {
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")) {
buffer.append(results.getResultString());
mResultText.setText(buffer.toString());
mResultText.setSelection(mResultText.length());
}
@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);
// }
}
};
if (isLast & cyclic) {
// TODO 最后的结果
Message message = Message.obtain();
message.what = 0x001;
han.sendMessageDelayed(message,100);
}
}
/**
* 显示结果
*/
private void printResult(RecognizerResult results) {
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
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
Log.d(TAG, "返回音频数据:"+data.length);
}
mIatResults.put(sn, text);
@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);
// }
}
};
StringBuffer resultBuffer = new StringBuffer();
for (String key : mIatResults.keySet()) {
resultBuffer.append(mIatResults.get(key));
}
mResultText.setText(resultBuffer.toString());
mResultText.setSelection(mResultText.length());
}
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字段
try {
JSONObject resultJson = new JSONObject(results.getResultString());
sn = resultJson.optString("sn");
} catch (JSONException e) {
e.printStackTrace();
}
// 识别回调错误
public void onError(SpeechError error) {
showTip(error.getPlainDescription(true));
}
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")) {
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 {
private void showTip(final String str) {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
mToast.show();
}
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中不显示错误码信息
//mIat.setParameter("view_tips_plain","false");
if (language.equals("zh_cn")) {
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));
// 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
// 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音
mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
// 设置音频保存路径保存音频格式支持pcmwav设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
}
//此处用于设置dialog中不显示错误码信息
//mIat.setParameter("view_tips_plain","false");
// 设置语音前端点:静音超时时间即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
@Override
protected void onDestroy() {
super.onDestroy();
if( null != mIat ){
// 退出时释放连接
mIat.cancel();
mIat.destroy();
}
}
// 设置语音后端点:后端点静音检测时间即用户停止说话多长时间内即认为不再输入 自动停止录音
mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
@Override
protected void onResume() {
// 开放统计 移动数据统计分析
/*FlowerCollector.onResume(IatDemo.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
@Override
protected void onPause() {
// 开放统计 移动数据统计分析
// 设置音频保存路径保存音频格式支持pcmwav.
mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
getExternalFilesDir("msc").getAbsolutePath() + "/iat.wav");
}
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查询解决方案");
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("读取音频流失败");
}
}
//执行音频流识别操作
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("读取音频流失败");
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mIat != null) {
// 退出时释放连接
mIat.cancel();
mIat.destroy();
}
}
}

View File

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

View File

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

View File

@ -1,169 +1,168 @@
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.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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
*/
public class IseDemo extends Activity implements OnClickListener {
private static String TAG = IseDemo.class.getSimpleName();
private final static String PREFER_NAME = "ise_settings";
private final static int REQUEST_CODE_SETTINGS = 1;
private static String TAG = IseDemo.class.getSimpleName();
private EditText mEvaTextEditText;
private EditText mResultEditText;
private Button mIseStartButton;
private Toast mToast;
private final static String PREFER_NAME = "ise_settings";
private final static int REQUEST_CODE_SETTINGS = 1;
// 评测语种
private String language;
// 评测题型
private String category;
// 结果等级
private String result_level;
private String mLastResult;
private SpeechEvaluator mIse;
// 评测监听接口
private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {
@Override
public void onResult(EvaluatorResult result, boolean isLast) {
Log.d(TAG, "evaluator result :" + isLast);
private EditText mEvaTextEditText;
private TextView mResultEditText;
private Button mIseStartButton;
private Toast mToast;
if (isLast) {
StringBuilder builder = new StringBuilder();
builder.append(result.getResultString());
if(!TextUtils.isEmpty(builder)) {
mResultEditText.setText(builder.toString());
}
mIseStartButton.setEnabled(true);
mLastResult = builder.toString();
showTip("评测结束");
}
}
// 评测语种
private String language;
// 评测题型
private String category;
// 结果等级
private String result_level;
@Override
public void onError(SpeechError error) {
mIseStartButton.setEnabled(true);
if(error != null) {
showTip("error:"+ error.getErrorCode() + "," + error.getErrorDescription());
mResultEditText.setText("");
mResultEditText.setHint("请点击“开始评测”按钮");
} else {
Log.d(TAG, "evaluator over");
}
}
private String mLastResult;
private SpeechEvaluator mIse;
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
Log.d(TAG, "evaluator begin");
}
@Override
public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
Log.d(TAG, "evaluator stoped");
}
// 评测监听接口
private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前音量:" + volume);
Log.d(TAG, "返回音频数据:"+data.length);
}
@Override
public void onResult(EvaluatorResult result, boolean isLast) {
Log.d(TAG, "evaluator result :" + isLast);
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
if (isLast) {
StringBuilder builder = new StringBuilder();
builder.append(result.getResultString());
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isedemo);
if (!TextUtils.isEmpty(builder)) {
mResultEditText.setText(builder.toString());
}
mIseStartButton.setEnabled(true);
mLastResult = builder.toString();
mIse = SpeechEvaluator.createEvaluator(IseDemo.this, null);
initUI();
setEvaText();
}
showTip("评测结束");
}
}
private void initUI() {
findViewById(R.id.image_ise_set).setOnClickListener(IseDemo.this);
mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text);
mResultEditText = (EditText)findViewById(R.id.ise_result_text);
mIseStartButton = (Button) findViewById(R.id.ise_start);
mIseStartButton.setOnClickListener(IseDemo.this);
findViewById(R.id.ise_parse).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_stop).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_cancel).setOnClickListener(IseDemo.this);
mToast = Toast.makeText(IseDemo.this, "", Toast.LENGTH_LONG);
}
@Override
public void onClick(View view) {
if( null == mIse ){
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip( "创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化" );
return;
}
switch (view.getId()) {
case R.id.image_ise_set:
Intent intent = new Intent(IseDemo.this, IseSettings.class);
startActivityForResult(intent, REQUEST_CODE_SETTINGS);
break;
case R.id.ise_start:
if (mIse == null) {
return;
}
String evaText = mEvaTextEditText.getText().toString();
mLastResult = null;
mResultEditText.setText("");
mResultEditText.setHint("请朗读以上内容");
mIseStartButton.setEnabled(false);
setParams();
int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener);
//以下方法为通过直接写入音频的方式进行评测业务
@Override
public void onError(SpeechError error) {
mIseStartButton.setEnabled(true);
if (error != null) {
showTip("error:" + error.getErrorCode() + "," + error.getErrorDescription());
mResultEditText.setText("");
mResultEditText.setHint("请点击“开始评测”按钮");
} else {
Log.d(TAG, "evaluator over");
}
}
@Override
public void onBeginOfSpeech() {
// 此回调表示sdk内部录音机已经准备好了用户可以开始语音输入
Log.d(TAG, "evaluator begin");
}
@Override
public void onEndOfSpeech() {
// 此回调表示检测到了语音的尾端点已经进入识别过程不再接受语音输入
Log.d(TAG, "evaluator stoped");
}
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前音量:" + volume);
Log.d(TAG, "返回音频数据:" + data.length);
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id当业务出错时将会话id提供给技术支持人员可用于查询会话日志定位出错原因
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.isedemo);
mIse = SpeechEvaluator.createEvaluator(IseDemo.this, null);
initUI();
setEvaText();
}
private void initUI() {
findViewById(R.id.image_ise_set).setOnClickListener(IseDemo.this);
mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text);
mResultEditText = (TextView) findViewById(R.id.ise_result_text);
mIseStartButton = (Button) findViewById(R.id.ise_start);
mIseStartButton.setOnClickListener(IseDemo.this);
findViewById(R.id.ise_parse).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_stop).setOnClickListener(IseDemo.this);
findViewById(R.id.ise_cancel).setOnClickListener(IseDemo.this);
mToast = Toast.makeText(IseDemo.this, "", Toast.LENGTH_LONG);
}
@Override
public void onClick(View view) {
if (null == mIse) {
// 创建单例失败 21001 错误为同样原因参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return;
}
switch (view.getId()) {
case R.id.image_ise_set:
Intent intent = new Intent(IseDemo.this, IseSettings.class);
startActivityForResult(intent, REQUEST_CODE_SETTINGS);
break;
case R.id.ise_start:
if (mIse == null) {
return;
}
String evaText = mEvaTextEditText.getText().toString();
mLastResult = null;
mResultEditText.setText("");
mResultEditText.setHint("请朗读以上内容");
mIseStartButton.setEnabled(false);
setParams();
int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener);
//以下方法为通过直接写入音频的方式进行评测业务
/*if (ret != ErrorCode.SUCCESS) {
showTip("识别失败,错误码:" + ret);
} else {
@ -182,135 +181,181 @@ public class IseDemo extends Activity implements OnClickListener {
}*/
break;
case R.id.ise_parse:
// 解析最终结果
if (!TextUtils.isEmpty(mLastResult)) {
XmlResultParser resultParser = new XmlResultParser();
Result result = resultParser.parse(mLastResult);
if (null != result) {
mResultEditText.setText(result.toString());
} 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
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE_SETTINGS == requestCode) {
setEvaText();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != mIse) {
mIse.destroy();
mIse = null;
}
}
// 设置评测试题
private void setEvaText() {
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
String text = "";
if ("en_us".equals(language)) {
if ("read_word".equals(category)) {
text = getString(R.string.text_en_word);
} else if ("read_sentence".equals(category)) {
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);
mResultEditText.setText("");
mLastResult = null;
mResultEditText.setHint("请点击“开始评测”按钮");
}
break;
case R.id.ise_parse:
// 解析最终结果
if (!TextUtils.isEmpty(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;
}
}
XmlResultParser resultParser = new XmlResultParser();
Result result = resultParser.parse(mLastResult);
if (null != result) {
mResultEditText.setText(result.toString());
} 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
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE_SETTINGS == requestCode) {
setEvaText();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != mIse) {
mIse.destroy();
mIse = null;
}
}
// 设置评测试题
private void setEvaText() {
SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
String text = "";
if ("en_us".equals(language)) {
switch (category) {
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;
}
} else {
// 中文评测
switch (category) {
case "read_syllable":
text = getString(R.string.text_cn_syllable);
break;
case "read_word":
text = getString(R.string.text_cn_word);
break;
case "read_sentence":
text = getString(R.string.text_cn_sentence);
break;
case "read_chapter":
text = getString(R.string.text_cn_chapter);
break;
}
}
mEvaTextEditText.setText(text);
mResultEditText.setText("");
mLastResult = null;
mResultEditText.setHint("请点击“开始评测”按钮");
}
private void showTip(String str) {
if (!TextUtils.isEmpty(str)) {
mToast.cancel();
mToast.setText(str);
mToast.show();
}
}
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");
}
private void showTip(String str) {
if(!TextUtils.isEmpty(str)) {
mToast.setText(str);
mToast.show();
}
}
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");
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设置路径为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
protected void onResume() {
// 开放统计 移动数据统计分析
/*FlowerCollector.onResume(IseDemo.this);
FlowerCollector.onPageStart(TAG);*/
super.onResume();
}
@Override
protected void onPause() {
/* // 开放统计 移动数据统计分析
FlowerCollector.onPageEnd(TAG);
FlowerCollector.onPause(IseDemo.this);*/
super.onPause();
}
}

View File

@ -1,252 +1,84 @@
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.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
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.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
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();
private Toast mToast;
private final int URL_REQUEST_CODE = 0X001;
private TextView edit_text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
initView();
requestPermissions();
}
@SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
edit_text = (TextView) findViewById(R.id.edit_text);
StringBuffer buf = new StringBuffer();
buf.append("当前APPID为");
buf.append(getString(R.string.app_id)+"\n");
buf.append(getString(R.string.example_explain));
edit_text.setText(buf);
requestPermissions();
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
//mscInit(null);//采用sdk默认url
SimpleAdapter listitemAdapter = new SimpleAdapter();
((ListView) findViewById(R.id.listview_main)).setAdapter(listitemAdapter);
private void initView() {
TextView tipTv = (TextView) findViewById(R.id.tip);
String buf = "当前APPID为" +
getString(R.string.app_id) + "\n" +
getString(R.string.example_explain);
tipTv.setText(buf);
// 语音转写
findViewById(R.id.iatBtn).setOnClickListener(v -> {
startActivity(new Intent(MainActivity.this, IatDemo.class));
});
// 语法识别
findViewById(R.id.asrBtn).setOnClickListener(v -> {
startActivity(new Intent(MainActivity.this, AsrDemo.class));
});
// 语义理解
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
public void onClick(View view) {
int tag = Integer.parseInt(view.getTag().toString());
Intent intent = null;
switch (tag) {
case 0:
// 语音转写
intent = new Intent(MainActivity.this, IatDemo.class);
break;
case 1:
// 语法识别
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) {
startActivity(intent);
}
}
private void requestPermissions() {
try {
if (Build.VERSION.SDK_INT >= 23) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
}, 0x0010);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Menu 列表
String items[] = { "立刻体验语音听写", "立刻体验语法识别", "立刻体验语义理解", "立刻体验语音合成",
"立刻体验语音评测", "立刻体验语音唤醒", "立刻体验声纹密码","立刻体验人脸识别"/*,"重置域名"*/ };
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
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;
import android.app.Application;
import com.iflytek.cloud.Setting;
import com.iflytek.cloud.SpeechUtility;
public class SpeechApp extends Application {
@Override
public void onCreate() {
// 应用程序入口处调用避免手机内存过小杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
// 如在Application中调用初始化需要在Mainifest中注册该Applicaiton
// 注意此接口在非主进程调用会返回null对象如需在非主进程使用语音功能请增加参数SpeechConstant.FORCE_LOGIN+"=true"
// 参数间使用半角,分隔
// 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
// 注意 appid 必须和下载的SDK保持一致否则会出现10407错误
SpeechUtility.createUtility(SpeechApp.this, "appid=" + getString(R.string.app_id));
// 以下语句用于设置日志开关默认开启设置成false时关闭语音云SDK日志打印
// Setting.setShowLog(false);
super.onCreate();
}
@Override
public void onCreate() {
// 应用程序入口处调用避免手机内存过小杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
// 如在Application中调用初始化需要在Mainifest中注册该Applicaiton
// 注意此接口在非主进程调用会返回null对象如需在非主进程使用语音功能请增加参数SpeechConstant.FORCE_LOGIN+"=true"
// 参数间使用半角,分隔
// 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
// 注意 appid 必须和下载的SDK保持一致否则会出现10407错误
SpeechUtility.createUtility(SpeechApp.this, "appid=" + getString(R.string.app_id));
// 以下语句用于设置日志开关默认开启设置成false时关闭语音云SDK日志打印
Setting.setShowLog(true);
super.onCreate();
}
}

View File

@ -1,6 +1,5 @@
package com.iflytek.voicedemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
@ -8,8 +7,6 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.MemoryFile;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
@ -29,368 +26,337 @@ import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechSynthesizer;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import java.io.RandomAccessFile;
public class TtsDemo extends Activity implements OnClickListener {
private static String TAG = TtsDemo.class.getSimpleName();
// 语音合成对象
private SpeechSynthesizer mTts;
private static String TAG = TtsDemo.class.getSimpleName();
// 语音合成对象
private SpeechSynthesizer mTts;
// 默认发音人
private String voicer = "xiaoyan";
private String[] mCloudVoicersEntries;
private String[] mCloudVoicersValue ;
String texts = "";
// 缓冲进度
private int mPercentForBuffering = 0;
// 播放进度
private int mPercentForPlaying = 0;
// 云端/本地单选按钮
private RadioGroup mRadioGroup;
// 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD;
// 默认发音人
private String voicer = "xiaoyan";
private Toast mToast;
private SharedPreferences mSharedPreferences;
private String[] mCloudVoicersEntries;
private String[] mCloudVoicersValue;
private String texts = "";
MemoryFile memFile;
public volatile long mTotalSize = 0;
// 缓冲进度
private int mPercentForBuffering = 0;
// 播放进度
private int mPercentForPlaying = 0;
private Vector<byte[]> container = new Vector<> ();
@SuppressLint("ShowToast")
public void onCreate(Bundle savedInstanceState) {
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);
// 云端发音人名称列表
mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);
mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE);
mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT);
}
// 云端/本地单选按钮
private RadioGroup mRadioGroup;
// 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD;
/**
* 初始化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);
mRadioGroup=((RadioGroup) findViewById(R.id.tts_rediogroup));
mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private Toast mToast;
private SharedPreferences mSharedPreferences;
private File pcmFile;
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.tts_radioCloud:
mEngineType = SpeechConstant.TYPE_CLOUD;
break;
default:
break;
}
public void onCreate(Bundle savedInstanceState) {
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);
}
}
} );
}
/**
* 初始化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);
@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");*/
mRadioGroup = ((RadioGroup) findViewById(R.id.tts_rediogroup));
mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
texts = ((EditText) findViewById(R.id.tts_text)).getText().toString();
// 设置参数
setParam();
int code = mTts.startSpeaking(texts, mTtsListener);
// /**
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.tts_radioCloud:
mEngineType = SpeechConstant.TYPE_CLOUD;
break;
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:
pcmFile = new File(getExternalCacheDir().getAbsolutePath(), "tts_pcmFile.pcm");
pcmFile.delete();
texts = ((EditText) findViewById(R.id.tts_text)).getText().toString();
// 设置参数
setParam();
// 合成并播放
int code = mTts.startSpeaking(texts, mTtsListener);
// /**
// * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
// * text:要合成的文本uri:需要保存的音频全路径listener:回调接口
// */
String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
// int code = mTts.synthesizeToUri(texts, path, mTtsListener);
if (code != ErrorCode.SUCCESS) {
showTip("语音合成失败,错误码: " + code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
break;
// 取消合成
case R.id.tts_cancel:
mTts.stopSpeaking();
break;
// 暂停播放
case R.id.tts_pause:
mTts.pauseSpeaking();
break;
// 继续播放
case R.id.tts_resume:
mTts.resumeSpeaking();
break;
// 选择发音人
case R.id.tts_btn_person_select:
showPresonSelectDialog();
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:
break;
}
}
// String path = getExternalFilesDir("msc").getAbsolutePath() + "/tts.pcm";
// // synthesizeToUri 只保存音频不进行播放
// int code = mTts.synthesizeToUri(texts, path, mTtsListener);
/**
* 初始化监听
*/
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调用移至这里
}
}
};
if (code != ErrorCode.SUCCESS) {
showTip("语音合成失败,错误码: " + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
}
break;
// 取消合成
case R.id.tts_cancel:
mTts.stopSpeaking();
break;
// 暂停播放
case R.id.tts_pause:
mTts.pauseSpeaking();
break;
// 继续播放
case R.id.tts_resume:
mTts.resumeSpeaking();
break;
// 选择发音人
case R.id.tts_btn_person_select:
showPersonSelectDialog();
break;
}
}
/**
* 合成回调监听
*/
private SynthesizerListener mTtsListener = new SynthesizerListener() {
@Override
public void onSpeakBegin() {
showTip("开始播放");
}
private int selectedNum = 0;
@Override
public void onSpeakPaused() {
showTip("暂停播放");
}
/**
* 发音人选择
*/
private void showPersonSelectDialog() {
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;
@Override
public void onSpeakResumed() {
showTip("继续播放");
}
default:
break;
}
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos,
String info) {
// 合成进度
Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
/**
* 初始化监听
*/
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 onSpeakProgress(int percent, int beginPos, int endPos) {
// 播放进度
Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForPlaying = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
/**
* 合成回调监听
*/
private SynthesizerListener mTtsListener = new SynthesizerListener() {
SpannableStringBuilder style=new SpannableStringBuilder(texts);
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 onSpeakBegin() {
showTip("开始播放");
}
@Override
public void onCompleted(SpeechError error) {
System.out.println("oncompleted");
if (error == null) {
// showTip("播放完成");
DebugLog.LogD("播放完成,"+container.size());
try {
for(int i=0;i<container.size();i++) {
writeToFile(container.get(i));
}
}catch (IOException e) {
@Override
public void onSpeakPaused() {
showTip("暂停播放");
}
}
FileUtil.saveFile(memFile,mTotalSize,Environment.getExternalStorageDirectory()+"/1.pcm");
@Override
public void onSpeakResumed() {
showTip("继续播放");
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos,
String info) {
// 合成进度
Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override
public void onSpeakProgress(int percent, int beginPos, int endPos) {
// 播放进度
Log.e("MscSpeechLog_", "percent =" + percent);
mPercentForPlaying = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
SpannableStringBuilder style = new SpannableStringBuilder(texts);
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));
}
}
@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("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 {
}
}
/**
* 给file追加数据
*/
private void appendFile(File file, byte[] buffer) {
try {
if (!file.exists()) {
boolean b = file.createNewFile();
}
RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
randomFile.seek(file.length());
randomFile.write(buffer);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

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

View File

@ -1,6 +1,5 @@
<?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:state_pressed="true" android:drawable="@color/list_backgroud_color"></item>
<item android:drawable="@drawable/layout_backgroud"></item>
</selector>

View File

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<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_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" 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="false" android:state_pressed="true" />
<item android:drawable="@drawable/setting"></item>
</selector>

View File

@ -1,85 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp" >
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:text="@string/title_face_idf"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:text="@string/title_face_idf"
android:textSize="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:gravity="center">
<ImageView
android:id="@+id/online_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:src="@drawable/no_photo" />
</LinearLayout>
<ImageView
android:id="@+id/online_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:src="@drawable/no_photo" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txt_groupid"
android:layout_gravity="center_horizontal"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txt_groupid"
android:layout_gravity="center_horizontal"
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
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<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
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>
<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>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,12 +5,12 @@
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
android:paddingRight="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" >
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
@ -28,32 +28,44 @@
android:background="@drawable/main_setting_btn_np" />
</RelativeLayout>
<EditText
android:id="@+id/ise_eva_text"
<ScrollView
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginBottom="5dp"
android:gravity="top|left"
android:textSize="20sp" />
android:layout_height="0dp"
android:layout_weight="1">
<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
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
android:orientation="horizontal">
<Button
android:id="@+id/ise_start"
@ -75,10 +87,10 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
android:orientation="horizontal">
<Button
android:id="@+id/ise_cancel"

View File

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

View File

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

View File

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

View File

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

View File

@ -4,15 +4,7 @@
android:layout_height="match_parent"
android:background="@drawable/list_bg_color"
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>

View File

@ -3,28 +3,101 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/layout_backgroud"
android:orientation="vertical" >
android:orientation="vertical">
<include layout="@layout/title" />
<TextView
android:id="@+id/edit_text"
android:id="@+id/tip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_"
android:layout_marginRight="@dimen/margin_"
android:textColor="@color/white"
android:textSize="@dimen/txt_size" />
<ListView
android:id="@+id/listview_main"
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:cacheColorHint="@color/white"
android:divider="@drawable/line_background"
android:dividerHeight="@dimen/line_height"
android:paddingBottom="5dp" />
android:layout_height="0dp"
android:layout_marginTop="20dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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>

View File

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

View File

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

View File

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

View File

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

View File

@ -3,12 +3,13 @@
<resources>
<!-- 画面背景色 -->
<drawable name="layout_backgroud">#000000</drawable>
<!-- 分割线背景色 -->
<drawable name="line_background">#161823</drawable>
<color name="white">#FFFFFF</color>
<color name="black">#000</color>
<!-- 控件按下时显示的颜色 -->
<color name="list_backgroud_color">#2fb3cb</color>
<color name="title_color">#0f8ec5</color>

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources>
<dimen name="margin_">10dp</dimen>
<dimen name="pading_">5dp</dimen>
<dimen name="btn_size">22sp</dimen>
<dimen name="txt_size">18sp</dimen>
<!-- 分割线高度 -->
<dimen name="line_height">1dp</dimen>
</resources>

File diff suppressed because one or more lines are too long

View File

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

View File

@ -1,27 +1,27 @@
<?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
android:key="iat_language_preference"
android:title="语言设置"
android:entries="@array/language_entries"
android:entryValues="@array/language_values"
android:summary="支持:普通话,粤语,英语 "
android:defaultValue="mandarin" />
android:defaultValue="mandarin" />
<EditTextPreference
android:key="iat_vadbos_preference"
android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:key="iat_vadbos_preference"
android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写5000其他4000"
android:defaultValue="5000" />
android:defaultValue="5000" />
<EditTextPreference
android:key="iat_vadeos_preference"
android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:key="iat_vadeos_preference"
android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写1800其他700 "
android:defaultValue="1800" />
android:defaultValue="1800" />
<ListPreference
android:key="iat_punc_preference"
@ -29,11 +29,11 @@
android:entries="@array/punc_entries"
android:entryValues="@array/punc_values"
android:summary="默认值:有标点 "
android:defaultValue="1" />
<CheckBoxPreference
android:key="@string/pref_key_iat_show"
android:title="@string/pref_title_iat_show"
android:defaultValue="true" />
android:defaultValue="1" />
<CheckBoxPreference
android:key="@string/pref_key_iat_show"
android:title="@string/pref_title_iat_show"
android:defaultValue="true" />
</PreferenceScreen>

View File

@ -1,47 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<ListPreference
<ListPreference
android:key="language"
android:title="评测语种"
android:summary=""
android:entries="@array/ise_language_entries"
android:entryValues="@array/ise_language_values"
android:defaultValue="zh_cn"/>
<ListPreference
<ListPreference
android:key="category"
android:title="评测题型"
android:summary=""
android:entries="@array/category_entries"
android:entryValues="@array/category_values"
android:defaultValue="read_sentence"/>
<ListPreference
<ListPreference
android:key="result_level"
android:title="结果等级"
android:summary=""
android:entries="@array/result_level_entries"
android:entryValues="@array/result_level_entries"
android:defaultValue="complete"/>
<EditTextPreference
<EditTextPreference
android:key="vad_bos"
android:title="前端点超时"
android:summary=""
android:defaultValue="5000"/>
<EditTextPreference
<EditTextPreference
android:key="vad_eos"
android:title="后端点超时"
android:summary=""
android:defaultValue="1800"/>
<EditTextPreference
<EditTextPreference
android:key="speech_timeout"
android:title="评测超时"
android:summary=""
android:defaultValue="-1"/>
</PreferenceScreen>

View File

@ -1,5 +1,5 @@
<?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
android:dialogTitle="请输入语速:在线(0-100)本地(0-200)"

View File

@ -1,39 +1,39 @@
<?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
android:key="understander_language_preference"
android:title="语言设置"
android:entries="@array/language_entries"
android:entryValues="@array/language_values"
android:summary="支持:普通话,粤语,英语 "
android:defaultValue="mandarin" />
android:defaultValue="mandarin" />
<EditTextPreference
android:key="understander_vadbos_preference"
android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:key="understander_vadbos_preference"
android:title="前端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写5000其他4000"
android:defaultValue="4000" />
android:defaultValue="4000" />
<EditTextPreference
android:key="understander_vadeos_preference"
android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:key="understander_vadeos_preference"
android:title="后端点超时"
android:dialogTitle="请输入时间(0-10000)ms"
android:summary="默认值短信转写1800其他700 "
android:defaultValue="700" />
android:defaultValue="700" />
<ListPreference
android:key="understander_punc_preference"
android:title="标点符号"
android:entries="@array/punc_entries"
android:entryValues="@array/punc_values"
android:summary="默认值:有标点 "
android:defaultValue="1" />
<!-- <CheckBoxPreference -->
<!-- android:key="nbest_preference" -->
<!-- android:title="@string/set_multiple_candidate_title" -->
<!-- android:summary="@string/set_multiple_candidate_summary" -->
<!-- android:defaultValue="false" /> -->
android:defaultValue="1" />
<!-- <CheckBoxPreference -->
<!-- android:key="nbest_preference" -->
<!-- android:title="@string/set_multiple_candidate_title" -->
<!-- android:summary="@string/set_multiple_candidate_summary" -->
<!-- android:defaultValue="false" /> -->
</PreferenceScreen>

View File

@ -1,17 +1,17 @@
<?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
android:key="url_preference"
android:title="域名设置"
android:entries="@array/machine_entries"
android:entryValues="@array/machine_values"
android:summary="支持:鲁谷,广州,森华 " />
android:summary="支持:鲁谷,广州,森华 " />
<EditTextPreference
android:key="url_edit"
android:title="输入域名(优先级较高) 格式参考:域名(+:端口)"
android:summary=""/>
android:summary="" />
</PreferenceScreen>

Binary file not shown.