diff --git a/.gitignore b/.gitignore
index 936749b5fbad8f80e5d5f278b47acdc725a323e2..37a4eb8b43d978ea05b2c6e3fb934f9b40dddd4d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,15 @@
-# IntelliJ IDEA
-.idea
*.iml
-
-# Gradle
-.gradle/
-build/
-
-# Local configuration file (sdk path, etc)
-local.properties
\ No newline at end of file
+.gradle
+/local.properties
+/.idea/caches
+/.idea/libraries
+/.idea/modules.xml
+/.idea/workspace.xml
+/.idea/navEditor.xml
+/.idea/assetWizardSettings.xml
+.DS_Store
+/build
+/captures
+.externalNativeBuild
+/entry/.preview
+.cxx
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bbfe2828256982026e31bbdee8deea3a4f837d86..8d30eb20c286af8878aff829ef5dfa68eac909f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,9 +1,2 @@
-Change Log
-==========
-
-
-## Version 1.0.1
-
-_2016-04-30_
-
-Initial release.
+## 0.0.1-SNAPSHOT
+ohos第一个版本,实现了原库的全部功能
diff --git a/LICENSE.txt b/LICENSE
similarity index 100%
rename from LICENSE.txt
rename to LICENSE
diff --git a/README.OPENSOURCE b/README.OPENSOURCE
new file mode 100644
index 0000000000000000000000000000000000000000..f5c598ea9fe38c9d4b80217e5eeb8e79229f4bf7
--- /dev/null
+++ b/README.OPENSOURCE
@@ -0,0 +1,10 @@
+[
+ {
+ "Name": "SpeechRecognitionView",
+ "License": " Apache License ",
+ "License File": " LICENSE ",
+ "Version Number": "1.2.2 ",
+ "Upstream URL": " https://github.com/zagum/SpeechRecognitionView",
+ "Description": "一种动画通过语音来控制变化"
+ }
+]
diff --git a/README.md b/README.md
index 5e2191624738bd8a4cfd091e3c26ba40d0505350..6d8115457fc2b366e17388930b47f842adf06f9e 100644
--- a/README.md
+++ b/README.md
@@ -1,173 +1,108 @@
-SpeechRecognitionView
-======================
-
-[](http://android-arsenal.com/details/1/3518)
-[](https://jitpack.io/#zagum/SpeechRecognitionView)
-
-"Google Now" style animation for [Speech Recognizer][1].
-
-
-
-
-Compatibility
--------------
-
-This library is compatible from API 15 (Android 4.0.3).
-
-
-Download
---------
-
-
-Add it in your root build.gradle at the end of repositories:
-
-```groovy
+# SpeechRecognitionView
+
+#### 项目介绍
+- 项目名称:语音识别动画
+- 所属系列:openharmony的第三方组件适配移植
+- 功能:一种动画通过语音来控制变化
+- 项目移植状态:主功能完成
+- 调用差异:无
+- 开发版本:sdk6,DevEco Studio2.2 Bate1
+- 基线版本:Releases 1.2.2
+
+#### 效果演示
+
+
+#### 安装教程
+
+1.在项目根目录下的build.gradle文件中,
+ ```gradle
allprojects {
repositories {
- ...
- maven { url "https://jitpack.io" }
+ maven {
+ url 'https://s01.oss.sonatype.org/content/repositories/snapshots/'
+ }
}
}
+ ```
+2.在entry模块的build.gradle文件中,
+ ```gradle
+ dependencies {
+ implementation('com.gitee.chinasoft_ohos:SpeechRecognitionView:0.0.1-SNAPSHOT')
+ ......
+ }
```
-Add the dependency
-
-```groovy
-dependencies {
- compile 'com.github.zagum:SpeechRecognitionView:1.2.2'
-}
-```
-
-
-Usage
------
+在sdk6,DevEco Studio2.2 Bate1下项目可直接运行
+如无法运行,删除项目.gradle,.idea,build,gradle,build.gradle文件,
+并依据自己的版本创建新项目,将新项目的对应文件复制到根目录下
-* Xml file:
+#### 使用说明
-Simply add view to your layout:
-
-``` xml
-
-```
-* Initialization:
-
-Init speech recognizer:
-``` java
-SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context);
-```
-
-Init RecognitionProgressView:
-``` java
-RecognitionProgressView recognitionProgressView = (RecognitionProgressView) findViewById(R.id.recognition_view);
-recognitionProgressView.setSpeechRecognizer(speechRecognizer);
-recognitionProgressView.setRecognitionListener(new RecognitionListenerAdapter() {
- @Override
- public void onResults(Bundle results) {
- showResults(results);
- }
-});
-```
-
-When SpeechRecognizer and RecognitionProgressView inited, use your speech recognizer as usual:
-``` java
-listen.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- startRecognition();
- }
-});
-
-private void startRecognition() {
- Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
- speechRecognizer.startListening(intent);
-}
-```
-
-Start and stop RecognitionProgressView animation:
-``` java
-recognitionProgressView.play();
-
-recognitionProgressView.stop();
+使用该库非常简单,只需查看提供的示例的源代码。
+```示例XML
+ ``
```
-* Customization:
-
-Set custom colors:
-``` java
-int[] colors = {
- ContextCompat.getColor(this, R.color.color1),
- ContextCompat.getColor(this, R.color.color2),
- ContextCompat.getColor(this, R.color.color3),
- ContextCompat.getColor(this, R.color.color4),
- ContextCompat.getColor(this, R.color.color5)
-};
-recognitionProgressView.setColors(colors);
+```java
+ int[] colors = {
+ Color.getIntColor("#3164d7"),
+ Color.getIntColor("#d92d29"),
+ Color.getIntColor("#eeaa10"),
+ Color.getIntColor("#3164d7"),
+ Color.getIntColor("#2e9641")
+ };
+ int[] heights = {20, 24, 18, 23, 16};
+ initIntent = new AsrIntent();
+ initIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM);
+ // 将FilePath修改为正确的地址,且文件路径需要给com.huawei.hiai进程授予可访问权限。
+ initIntent.setFilePath(this.getAbilityPackageContext().getExternalCacheDir().getAbsolutePath());
+ recognitionProgressView = (RecognitionProgressView) findComponentById(ResourceTable.Id_recognition_view);
+ recognitionProgressView.setRecognitionListener(new RecognitionListenerAdapter() {
+ @Override
+ public void onResults(PacMap results) {
+ showResults(results);
+ }
+ });
+ recognitionProgressView.setColors(colors);
+ recognitionProgressView.setBarMaxHeightsInDp(heights);
+ recognitionProgressView.setCircleRadiusInDp(2);
+ recognitionProgressView.setSpacingInDp(2);
+ recognitionProgressView.setIdleStateAmplitudeInDp(2);
+ recognitionProgressView.setRotationRadiusInDp(10);
+ recognitionProgressView.play();
```
-Set custom bars heights:
-``` java
-int[] heights = {60, 76, 58, 80, 55};
-recognitionProgressView.setBarMaxHeightsInDp(heights);
-```
+#### 测试信息
-Set custom circle radius/spacing between circles/idle animation amolitude size/rotation animation radius:
-``` java
-recognitionProgressView.setCircleRadiusInDp(2);
-recognitionProgressView.setSpacingInDp(2);
-recognitionProgressView.setIdleStateAmplitudeInDp(2);
-recognitionProgressView.setRotationRadiusInDp(10);
-```
-Don't forget to add permission to your AndroidManifest.xml file
-``` xml
-
-```
+CodeCheck代码测试无异常
+CloudTest代码测试无异常
-* Warning
-
-From [Android Documentation](http://developer.android.com/reference/android/speech/RecognitionListener.html#onRmsChanged(float))
-For ```java public abstract void onRmsChanged (float rmsdB)``` callback ```There is no guarantee that this method will be called.```,
-so if this callback does not return values the Bars animation will be skipped.
-
-I found some hack to make it working every time you want to start speech recognition:
-``` java
-listen.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- startRecognition();
- recognitionProgressView.postDelayed(new Runnable() {
- @Override
- public void run() {
- startRecognition();
- }
- }, 50);
- }
-});
-```
+病毒安全检测通过
+当前版本demo功能与原组件基本无差异
-License
--------
+#### 版本迭代
- Copyright 2016 Evgenii Zagumennyi
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+- 0.0.1-SNAPSHOT
+#### 版权和许可信息
-[1]: http://developer.android.com/intl/ru/reference/android/speech/SpeechRecognizer.html
+ Copyright 2016 Evgenii Zagumennyi
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/art/speechrecognitionview.gif b/art/speechrecognitionview.gif
deleted file mode 100644
index 2bef2696cbeb78cc10cfa7c1f54f7f4ca88c17e4..0000000000000000000000000000000000000000
Binary files a/art/speechrecognitionview.gif and /dev/null differ
diff --git a/build.gradle b/build.gradle
index 899c0a842b50592910c0870657b5e1ee118a723c..a8f39f4d73e08335c056116fea91992d30b9da6d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,29 +1,41 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+apply plugin: 'com.huawei.ohos.app'
+
+//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
+ohos {
+ compileSdkVersion 5
+ defaultConfig {
+ compatibleSdkVersion 4
+ }
+}
+
buildscript {
- repositories {
- google()
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:3.1.4'
- }
+ repositories {
+ maven {
+ url 'https://repo.huaweicloud.com/repository/maven/'
+ }
+ maven {
+ url 'https://developer.huawei.com/repo/'
+ }
+ }
+ dependencies {
+ classpath 'com.huawei.ohos:hap:2.4.5.0'
+ classpath 'com.huawei.ohos:decctest:1.2.4.1'
+ }
}
allprojects {
- repositories {
- google()
- jcenter()
- maven { url "https://jitpack.io" }
- }
-}
+ repositories {
+ maven {
-ext {
- minSdkVersion = 15
- compileSdkVersion = 27
- buildToolsVersion = '27.0.3'
+ url 'https://s01.oss.sonatype.org/content/repositories/snapshots/'
- supportAppCompat = 'com.android.support:appcompat-v7:27.1.1'
+ }
+ maven {
+ url 'https://repo.huaweicloud.com/repository/maven/'
+ }
+ maven {
+ url 'https://developer.huawei.com/repo/'
+ }
+ }
}
-
-task clean(type: Delete) {
- delete rootProject.buildDir
-}
\ No newline at end of file
diff --git a/entry/.gitignore b/entry/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..796b96d1c402326528b4ba3c12ee9d92d0e212e9
--- /dev/null
+++ b/entry/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/entry/build.gradle b/entry/build.gradle
new file mode 100644
index 0000000000000000000000000000000000000000..8ba888ea2530f0a17bbc3c4bf31b37f8ad187d6d
--- /dev/null
+++ b/entry/build.gradle
@@ -0,0 +1,31 @@
+apply plugin: 'com.huawei.ohos.hap'
+apply plugin: 'com.huawei.ohos.decctest'
+//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
+ohos {
+
+ compileSdkVersion 5
+ defaultConfig {
+ compatibleSdkVersion 4
+ }
+ buildTypes {
+ release {
+ proguardOpt {
+ proguardEnabled false
+ rulesFiles 'proguard-rules.pro'
+ }
+ }
+ }
+
+}
+
+dependencies {
+ implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])
+ testImplementation 'junit:junit:4.13'
+ ohosTestImplementation 'com.huawei.ohos.testkit:runner:1.0.0.200'
+ compile project(":speechrecognitionview")
+ implementation('com.gitee.chinasoft_ohos:rippleview:0.0.1-SNAPSHOT')
+ implementation 'io.openharmony.tpc.thirdlib:XXPermissions:1.0.2'
+}
+decc {
+ supportType = ['html', 'xml']
+}
diff --git a/entry/proguard-rules.pro b/entry/proguard-rules.pro
new file mode 100644
index 0000000000000000000000000000000000000000..f7666e47561d514b2a76d5a7dfbb43ede86da92a
--- /dev/null
+++ b/entry/proguard-rules.pro
@@ -0,0 +1 @@
+# config module specific ProGuard rules here.
\ No newline at end of file
diff --git a/entry/src/main/config.json b/entry/src/main/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..d476ea0c29e185f061bba69f43d41c08ea92494b
--- /dev/null
+++ b/entry/src/main/config.json
@@ -0,0 +1,105 @@
+{
+ "app": {
+ "bundleName": "com.github.zagum.speechrecognitionview.sample",
+ "vendor": "github",
+ "version": {
+ "code": 1000000,
+ "name": "1.0.0"
+ }
+ },
+ "deviceConfig": {},
+ "module": {
+ "package": "com.github.zagum.speechrecognitionview.sample",
+ "name": ".MyApplication",
+ "mainAbility": "com.github.zagum.speechrecognitionview.sample.MainAbility",
+ "deviceType": [
+ "phone"
+ ],
+ "metaData": {
+ "customizeData": [
+ {
+ "name": "hwc-theme",
+ "value": "androidhwext:style/Theme.Emui.NoTitleBar",
+ "extra": ""
+ }
+ ]
+ },
+ "reqPermissions": [
+ {
+ "name": "ohos.permission.MICROPHONE",
+ "reason": "需要麦克风",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.READ_MEDIA",
+ "reason": "需要存储",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.WRITE_MEDIA",
+ "reason": "需要存储",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.RECORD_AUDIO",
+ "reason": "需要存储",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.READ_USER_STORAGE",
+ "reason": "需要存储",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.WRITE_USER_STORAGE",
+ "reason": "需要存储",
+ "usedScene":{
+ "ability": ["com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice"],
+ "when": "always"
+ }
+ }
+ ],
+ "distro": {
+ "deliveryWithInstall": true,
+ "moduleName": "entry",
+ "moduleType": "entry",
+ "installationFree": false
+ },
+ "abilities": [
+ {
+ "skills": [
+ {
+ "entities": [
+ "entity.system.home"
+ ],
+ "actions": [
+ "action.system.home"
+ ]
+ }
+ ],
+ "orientation": "unspecified",
+ "name": "com.github.zagum.speechrecognitionview.sample.MainAbility",
+ "icon": "$media:icon",
+ "description": "$string:mainability_description",
+ "label": "$string:entry_MainAbility",
+ "type": "page",
+ "launchType": "standard"
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MainAbility.java b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MainAbility.java
new file mode 100644
index 0000000000000000000000000000000000000000..f31195b585eb31afdd9c5803244075cbe6b5e3b3
--- /dev/null
+++ b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MainAbility.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2021 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.zagum.speechrecognitionview.sample;
+
+import com.github.zagum.speechrecognitionview.sample.slice.MainAbilitySlice;
+import ohos.aafwk.ability.Ability;
+import ohos.aafwk.content.Intent;
+
+public class MainAbility extends Ability {
+ @Override
+ public void onStart(Intent intent) {
+ super.onStart(intent);
+ super.setMainRoute(MainAbilitySlice.class.getName());
+ }
+}
diff --git a/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MyApplication.java b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MyApplication.java
new file mode 100644
index 0000000000000000000000000000000000000000..7e8550932ae97f6490f94caddfc0511dbf090109
--- /dev/null
+++ b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/MyApplication.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2021 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.zagum.speechrecognitionview.sample;
+
+import ohos.aafwk.ability.AbilityPackage;
+
+public class MyApplication extends AbilityPackage {
+ @Override
+ public void onInitialize() {
+ super.onInitialize();
+ }
+}
diff --git a/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/slice/MainAbilitySlice.java b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/slice/MainAbilitySlice.java
new file mode 100644
index 0000000000000000000000000000000000000000..cb716ac6a32142b0fc24fd08add1b8fb23613df0
--- /dev/null
+++ b/entry/src/main/java/com/github/zagum/speechrecognitionview/sample/slice/MainAbilitySlice.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2021 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.zagum.speechrecognitionview.sample.slice;
+
+import com.github.zagum.speechrecognitionview.RecognitionProgressView;
+import com.github.zagum.speechrecognitionview.adapters.RecognitionListenerAdapter;
+import com.github.zagum.speechrecognitionview.sample.ResourceTable;
+import com.hjq.permissions.OnPermission;
+import com.hjq.permissions.XXPermissions;
+import com.indris.material.RippleView;
+import ohos.aafwk.ability.AbilitySlice;
+import ohos.aafwk.content.Intent;
+import ohos.agp.components.Component;
+import ohos.agp.components.Text;
+import ohos.agp.text.Font;
+import ohos.agp.utils.Color;
+import ohos.agp.window.dialog.ToastDialog;
+import ohos.ai.asr.AsrClient;
+import ohos.ai.asr.AsrIntent;
+import ohos.app.dispatcher.TaskDispatcher;
+import ohos.utils.PacMap;
+import java.util.List;
+
+public class MainAbilitySlice extends AbilitySlice {
+ private AsrClient asrClient;
+ private AsrIntent initIntent;
+ private RecognitionProgressView recognitionProgressView;
+ private final static String TAG = "MainThisClass->";
+
+ @Override
+ public void onStart(Intent intent) {
+ super.onStart(intent);
+ super.setUIContent(ResourceTable.Layout_ability_main);
+ getWindow().setStatusBarColor(Color.getIntColor("#3b4dac"));
+ int[] colors = {
+ Color.getIntColor("#3164d7"),
+ Color.getIntColor("#d92d29"),
+ Color.getIntColor("#eeaa10"),
+ Color.getIntColor("#3164d7"),
+ Color.getIntColor("#2e9641")
+ };
+ Text title = (Text) findComponentById(ResourceTable.Id_title);
+ title.setFont(Font.DEFAULT_BOLD);
+ int[] heights = {24, 28, 22, 27, 20};
+ initIntent = new AsrIntent();
+ initIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM);
+ // 将FilePath修改为正确的地址,且文件路径需要给com.huawei.hiai进程授予可访问权限。
+ initIntent.setFilePath(this.getAbilityPackageContext().getExternalCacheDir().getAbsolutePath());
+ recognitionProgressView = (RecognitionProgressView) findComponentById(ResourceTable.Id_recognition_view);
+ recognitionProgressView.setRecognitionListener(new RecognitionListenerAdapter() {
+ @Override
+ public void onResults(PacMap results) {
+ showResults(results);
+ }
+
+ @Override
+ public void onError(int i) {
+ System.out.println("onError" + "======onError:"+i);
+
+// if(i == 5){
+// asrClient.stopListening(); // 停止识别
+// asrClient.cancel(); // 取消识别
+// asrClient.destroy();
+// asrClient = null ;
+// startRecognition();
+// }
+// super.onError(i);
+ }
+ });
+ asrClient = AsrClient.createAsrClient(this).orElse(null);
+ recognitionProgressView.setColors(colors);
+ recognitionProgressView.setBarMaxHeightsInDp(heights);
+ recognitionProgressView.setCircleRadiusInDp(2);
+ recognitionProgressView.setSpacingInDp(6);
+ recognitionProgressView.setIdleStateAmplitudeInDp(2);
+ recognitionProgressView.setRotationRadiusInDp(10);
+ recognitionProgressView.play();
+ RippleView click_one = (RippleView) findComponentById(ResourceTable.Id_click_one);
+ click_one.setClickedListener(new Component.ClickedListener() {
+ @Override
+ public void onClick(Component component) {
+ getPermissions();
+ }
+ });
+ RippleView click_two = (RippleView) findComponentById(ResourceTable.Id_click_two);
+ click_two.setClickedListener(new Component.ClickedListener() {
+ @Override
+ public void onClick(Component component) {
+ recognitionProgressView.stop();
+ recognitionProgressView.play();
+ }
+ });
+ }
+
+ @Override
+ public void onActive() {
+ super.onActive();
+ }
+
+ @Override
+ protected void onStop() {
+ asrClient.stopListening(); // 停止识别
+ asrClient.cancel(); // 取消识别
+ asrClient.destroy();
+ super.onStop();
+ }
+
+
+ private boolean hasSpecked = false;
+
+ private void startRecognition() {
+ TaskDispatcher taskDispatcher = getAbility().getMainTaskDispatcher();
+ taskDispatcher.asyncDispatch(
+ new Runnable() {
+ @Override
+ public void run() {
+ System.out.println("hasPermission" + "taskDispatcher");
+ hasSpecked = true;
+ recognitionProgressView.setSpeechRecognizer(asrClient);
+
+ }
+ });
+ }
+
+ private void getPermissions() {
+ if (hasSpecked) {
+ recognitionProgressView.stop();
+ recognitionProgressView.play();
+ return;
+ }
+ XXPermissions.with(this).permission("ohos.permission.MICROPHONE", "ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
+ "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE").request(new OnPermission() {
+ @Override
+ public void hasPermission(List list, boolean b) {
+ System.out.println("hasPermission" + "hasPermission===" + b);
+
+ if (b) {
+ startRecognition();
+ } else {
+ terminateAbility();
+ }
+ }
+
+ @Override
+ public void noPermission(List list, boolean b) {
+ if (b) {
+ // 如果是被永久拒绝就跳转到应用权限系统设置页面
+ String[] permissions = new String[list.size()];
+ list.toArray(permissions);
+ XXPermissions.startPermissionActivity(MainAbilitySlice.this, permissions, this);
+ } else {
+ new ToastDialog(getContext()).setText("获取权限失败").show();
+ terminateAbility();
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onForeground(Intent intent) {
+ super.onForeground(intent);
+ }
+
+
+ private void showResults(PacMap results) {
+// ArrayList matches = results
+// .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
+// Toast.makeText(this, matches.get(0), Toast.LENGTH_LONG).show();
+ }
+
+
+}
diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..c2a6b66cf9bbe3634a9332007717dfd5f2db38bf
--- /dev/null
+++ b/entry/src/main/resources/base/element/string.json
@@ -0,0 +1,16 @@
+{
+ "string": [
+ {
+ "name": "entry_MainAbility",
+ "value": "entry_MainAbility"
+ },
+ {
+ "name": "mainability_description",
+ "value": "Java_Empty Ability"
+ },
+ {
+ "name": "mainability_HelloWorld",
+ "value": "Hello World"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/entry/src/main/resources/base/graphic/background_ability_main.xml b/entry/src/main/resources/base/graphic/background_ability_main.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c0c0a3df480fa387a452b9c40ca191cc918a3fc0
--- /dev/null
+++ b/entry/src/main/resources/base/graphic/background_ability_main.xml
@@ -0,0 +1,6 @@
+
+
+
+
\ No newline at end of file
diff --git a/entry/src/main/resources/base/layout/ability_main.xml b/entry/src/main/resources/base/layout/ability_main.xml
new file mode 100644
index 0000000000000000000000000000000000000000..3594c6b1fed52544cd682c4eae7d86ccbaf4c747
--- /dev/null
+++ b/entry/src/main/resources/base/layout/ability_main.xml
@@ -0,0 +1,76 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/entry/src/main/resources/base/media/icon.png b/entry/src/main/resources/base/media/icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c
Binary files /dev/null and b/entry/src/main/resources/base/media/icon.png differ
diff --git a/entry/src/main/resources/en/element/string.json b/entry/src/main/resources/en/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..75dfd169090c9828ded8c42e2edf576139055c98
--- /dev/null
+++ b/entry/src/main/resources/en/element/string.json
@@ -0,0 +1,16 @@
+{
+ "string": [
+ {
+ "name": "entry_MainAbility",
+ "value": "speechrecognitionview"
+ },
+ {
+ "name": "mainability_description",
+ "value": "Java_Empty Ability"
+ },
+ {
+ "name": "mainability_HelloWorld",
+ "value": "Hello World"
+ }
+ ]
+}
diff --git a/entry/src/main/resources/zh/element/string.json b/entry/src/main/resources/zh/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..624fd5be49eadeb1368b0275ad7fe2f2d8279648
--- /dev/null
+++ b/entry/src/main/resources/zh/element/string.json
@@ -0,0 +1,16 @@
+{
+ "string": [
+ {
+ "name": "entry_MainAbility",
+ "value": "speechrecognitionview"
+ },
+ {
+ "name": "mainability_description",
+ "value": "Java_Empty Ability"
+ },
+ {
+ "name": "mainability_HelloWorld",
+ "value": "你好,世界"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/ExampleOhosTest.java b/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/ExampleOhosTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..c0437de339f0da8689993c02e77984ca8781de8a
--- /dev/null
+++ b/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/ExampleOhosTest.java
@@ -0,0 +1,14 @@
+package com.github.zagum.speechrecognitionview.sample;
+
+import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class ExampleOhosTest {
+ @Test
+ public void testBundleName() {
+ final String actualBundleName = AbilityDelegatorRegistry.getArguments().getTestBundleName();
+ assertEquals("com.github.zagum.speechrecognitionview.sample", actualBundleName);
+ }
+}
\ No newline at end of file
diff --git a/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/RecognitionProgressViewTest.java b/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/RecognitionProgressViewTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..69e4a7e151c519ea31e0151600d4c6a13a50ad04
--- /dev/null
+++ b/entry/src/ohosTest/java/com/github/zagum/speechrecognitionview/sample/RecognitionProgressViewTest.java
@@ -0,0 +1,87 @@
+package com.github.zagum.speechrecognitionview.sample;
+
+import com.github.zagum.speechrecognitionview.RecognitionProgressView;
+import com.github.zagum.speechrecognitionview.util.DensityUtils;
+import ohos.agp.text.Font;
+import ohos.app.Context;
+import org.junit.Test;
+
+public class RecognitionProgressViewTest {
+
+ @Test
+ public void setSpeechRecognizer() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("/com.github.zagum.speechrecognitionview.sample");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setRecognitionListener() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void play() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void stop() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setSingleColor() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setColors() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setBarMaxHeightsInDp() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setCircleRadiusInDp() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setSpacingInDp() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setIdleStateAmplitudeInDp() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+
+ @Test
+ public void setRotationRadiusInDp() {
+ DensityUtils densityUtils = new DensityUtils();
+ Font font = densityUtils.font("bottif.tff");
+ System.out.println(font);
+ }
+}
\ No newline at end of file
diff --git a/entry/src/test/java/com/github/zagum/speechrecognitionview/sample/ExampleTest.java b/entry/src/test/java/com/github/zagum/speechrecognitionview/sample/ExampleTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..1bd8857e7787a8f67a16369c0ada5a5d84da4cf9
--- /dev/null
+++ b/entry/src/test/java/com/github/zagum/speechrecognitionview/sample/ExampleTest.java
@@ -0,0 +1,9 @@
+package com.github.zagum.speechrecognitionview.sample;
+
+import org.junit.Test;
+
+public class ExampleTest {
+ @Test
+ public void onStart() {
+ }
+}
diff --git a/gradle.properties b/gradle.properties
deleted file mode 100644
index 1d3591c8a4c9c29578c36c87f80c05a6aea3ee3f..0000000000000000000000000000000000000000
--- a/gradle.properties
+++ /dev/null
@@ -1,18 +0,0 @@
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 05ef575b0cd0173fc735f2857ce4bd594ce4f6bd..490fda8577df6c95960ba7077c43220e5bb2c0d9 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index f7581b0c9f8680014f6f013b81297fd4f28713ad..f59159e865d4b59feb1b8c44b001f62fc5d58df4 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,5 @@
-#Thu Aug 30 11:14:58 MSK 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
+distributionUrl=https\://repo.huaweicloud.com/gradle/gradle-6.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
diff --git a/gradlew b/gradlew
deleted file mode 100755
index 9d82f78915133e1c35a6ea51252590fb38efac2f..0000000000000000000000000000000000000000
--- a/gradlew
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=`cygpath --unix "$JAVACMD"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
deleted file mode 100644
index aec99730b4e8fcd90b57a0e8e01544fea7c31a89..0000000000000000000000000000000000000000
--- a/gradlew.bat
+++ /dev/null
@@ -1,90 +0,0 @@
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
diff --git a/img/demo.gif b/img/demo.gif
new file mode 100644
index 0000000000000000000000000000000000000000..ff003c4a77cb0536b0602b68b98356248d400679
Binary files /dev/null and b/img/demo.gif differ
diff --git a/settings.gradle b/settings.gradle
index 68045c160a2e982b48b3f18fe6c9ec5219a11486..3d045eb8c3bacb77b7680ccff27edd3671c336b8 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,2 +1 @@
-include ':speechrecognitionview'
-include ':speechrecognitionview-sample'
\ No newline at end of file
+include ':entry', ':speechrecognitionview'
diff --git a/speechrecognitionview-sample/build.gradle b/speechrecognitionview-sample/build.gradle
deleted file mode 100644
index eb3731f25a3ee5ec9b22d5d9657e6bafb007577d..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/build.gradle
+++ /dev/null
@@ -1,18 +0,0 @@
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion rootProject.ext.compileSdkVersion
- buildToolsVersion rootProject.ext.buildToolsVersion
-
- defaultConfig {
- applicationId "com.github.zagum.speechrecognitionview.sample"
- minSdkVersion rootProject.ext.minSdkVersion
- targetSdkVersion rootProject.ext.compileSdkVersion
- versionCode 1
- versionName "1.0"
- }
-}
-
-dependencies {
- implementation 'com.github.zagum:SpeechRecognitionView:1.2.2'
-}
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/AndroidManifest.xml b/speechrecognitionview-sample/src/main/AndroidManifest.xml
deleted file mode 100644
index b70c96f502c3979c23ba04418250bedc6808723f..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/java/com/github/zagum/speechrecognitionview/sample/MainActivity.java b/speechrecognitionview-sample/src/main/java/com/github/zagum/speechrecognitionview/sample/MainActivity.java
deleted file mode 100644
index db3d652dae3e1f46c208da0b45337be7c19d8bb1..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/java/com/github/zagum/speechrecognitionview/sample/MainActivity.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2016 Evgenii Zagumennyi
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.github.zagum.speechrecognitionview.sample;
-
-import android.Manifest;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.os.Bundle;
-import android.speech.RecognizerIntent;
-import android.speech.SpeechRecognizer;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.content.ContextCompat;
-import android.support.v7.app.AppCompatActivity;
-import android.view.View;
-import android.widget.Button;
-import android.widget.Toast;
-import com.github.zagum.speechrecognitionview.RecognitionProgressView;
-import com.github.zagum.speechrecognitionview.adapters.RecognitionListenerAdapter;
-import java.util.ArrayList;
-
-public class MainActivity extends AppCompatActivity {
- private static final String TAG = "MainActivity";
- private static final int REQUEST_RECORD_AUDIO_PERMISSION_CODE = 1;
-
- private SpeechRecognizer speechRecognizer;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- int[] colors = {
- ContextCompat.getColor(this, R.color.color1),
- ContextCompat.getColor(this, R.color.color2),
- ContextCompat.getColor(this, R.color.color3),
- ContextCompat.getColor(this, R.color.color4),
- ContextCompat.getColor(this, R.color.color5)
- };
-
- int[] heights = { 20, 24, 18, 23, 16 };
-
- speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
-
- final RecognitionProgressView recognitionProgressView = (RecognitionProgressView) findViewById(R.id.recognition_view);
- recognitionProgressView.setSpeechRecognizer(speechRecognizer);
- recognitionProgressView.setRecognitionListener(new RecognitionListenerAdapter() {
- @Override
- public void onResults(Bundle results) {
- showResults(results);
- }
- });
- recognitionProgressView.setColors(colors);
- recognitionProgressView.setBarMaxHeightsInDp(heights);
- recognitionProgressView.setCircleRadiusInDp(2);
- recognitionProgressView.setSpacingInDp(2);
- recognitionProgressView.setIdleStateAmplitudeInDp(2);
- recognitionProgressView.setRotationRadiusInDp(10);
- recognitionProgressView.play();
-
- Button listen = (Button) findViewById(R.id.listen);
- Button reset = (Button) findViewById(R.id.reset);
-
- listen.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (ContextCompat.checkSelfPermission(MainActivity.this,
- Manifest.permission.RECORD_AUDIO)
- != PackageManager.PERMISSION_GRANTED) {
- requestPermission();
- } else {
- startRecognition();
- recognitionProgressView.postDelayed(new Runnable() {
- @Override
- public void run() {
- startRecognition();
- }
- }, 50);
- }
- }
- });
-
- reset.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- recognitionProgressView.stop();
- recognitionProgressView.play();
- }
- });
- }
-
- @Override
- protected void onDestroy() {
- if (speechRecognizer != null) {
- speechRecognizer.destroy();
- }
- super.onDestroy();
- }
-
- private void startRecognition() {
- Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en");
- speechRecognizer.startListening(intent);
- }
-
- private void showResults(Bundle results) {
- ArrayList matches = results
- .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
- Toast.makeText(this, matches.get(0), Toast.LENGTH_LONG).show();
- }
-
- private void requestPermission() {
- if (ActivityCompat.shouldShowRequestPermissionRationale(this,
- Manifest.permission.RECORD_AUDIO)) {
- Toast.makeText(this, "Requires RECORD_AUDIO permission", Toast.LENGTH_SHORT).show();
- } else {
- ActivityCompat.requestPermissions(this,
- new String[] { Manifest.permission.RECORD_AUDIO },
- REQUEST_RECORD_AUDIO_PERMISSION_CODE);
- }
- }
-}
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/res/layout/activity_main.xml b/speechrecognitionview-sample/src/main/res/layout/activity_main.xml
deleted file mode 100644
index 69128417f5b589b8f3fca6209439a1fb482c7ccf..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/res/layout/activity_main.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/res/mipmap-hdpi/ic_launcher.png b/speechrecognitionview-sample/src/main/res/mipmap-hdpi/ic_launcher.png
deleted file mode 100644
index cde69bcccec65160d92116f20ffce4fce0b5245c..0000000000000000000000000000000000000000
Binary files a/speechrecognitionview-sample/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ
diff --git a/speechrecognitionview-sample/src/main/res/mipmap-mdpi/ic_launcher.png b/speechrecognitionview-sample/src/main/res/mipmap-mdpi/ic_launcher.png
deleted file mode 100644
index c133a0cbd379f5af6dbf1a899a0293ca5eccfad0..0000000000000000000000000000000000000000
Binary files a/speechrecognitionview-sample/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ
diff --git a/speechrecognitionview-sample/src/main/res/mipmap-xhdpi/ic_launcher.png b/speechrecognitionview-sample/src/main/res/mipmap-xhdpi/ic_launcher.png
deleted file mode 100644
index bfa42f0e7b91d006d22352c9ff2f134e504e3c1d..0000000000000000000000000000000000000000
Binary files a/speechrecognitionview-sample/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/speechrecognitionview-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png b/speechrecognitionview-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
deleted file mode 100644
index 324e72cdd7480cb983fa1bcc7ce686e51ef87fe7..0000000000000000000000000000000000000000
Binary files a/speechrecognitionview-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ
diff --git a/speechrecognitionview-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/speechrecognitionview-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
deleted file mode 100644
index aee44e138434630332d88b1680f33c4b24c70ab3..0000000000000000000000000000000000000000
Binary files a/speechrecognitionview-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ
diff --git a/speechrecognitionview-sample/src/main/res/values/colors.xml b/speechrecognitionview-sample/src/main/res/values/colors.xml
deleted file mode 100644
index b9dddf015a8f20e85a9fa53752b24656dad88eaa..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/res/values/colors.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
- #3F51B5
- #303F9F
- #FF4081
- #3164d7
- #d92d29
- #eeaa10
- #3164d7
- #2e9641
-
-
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/res/values/strings.xml b/speechrecognitionview-sample/src/main/res/values/strings.xml
deleted file mode 100644
index 63b4474a62f3e5bdfd404346cedb24ad40ab2da5..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/res/values/strings.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
-
- SpeechRecognitionView
-
-
\ No newline at end of file
diff --git a/speechrecognitionview-sample/src/main/res/values/styles.xml b/speechrecognitionview-sample/src/main/res/values/styles.xml
deleted file mode 100644
index 89d10be7da70344862151232fa85930ac0923dd9..0000000000000000000000000000000000000000
--- a/speechrecognitionview-sample/src/main/res/values/styles.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/speechrecognitionview/.gitignore b/speechrecognitionview/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..796b96d1c402326528b4ba3c12ee9d92d0e212e9
--- /dev/null
+++ b/speechrecognitionview/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/speechrecognitionview/build.gradle b/speechrecognitionview/build.gradle
index c3064e90827efaf9e06460db88d3c614eeb2d4fe..4fbb637aa410ab68ba5e4e521b596585f2a614e1 100644
--- a/speechrecognitionview/build.gradle
+++ b/speechrecognitionview/build.gradle
@@ -1,14 +1,24 @@
-apply plugin: 'com.android.library'
-
-android {
- compileSdkVersion rootProject.ext.compileSdkVersion
- buildToolsVersion rootProject.ext.buildToolsVersion
-
+apply plugin: 'com.huawei.ohos.library'
+//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
+ohos {
+ compileSdkVersion 5
defaultConfig {
- minSdkVersion rootProject.ext.minSdkVersion
+ compatibleSdkVersion 4
+ }
+ buildTypes {
+ release {
+ proguardOpt {
+ proguardEnabled false
+ rulesFiles 'proguard-rules.pro'
+ }
+ }
}
+
}
dependencies {
- compile rootProject.ext.supportAppCompat
-}
\ No newline at end of file
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
+ testImplementation 'junit:junit:4.13'
+ implementation('com.alibaba:fastjson:1.2.4')
+
+}
diff --git a/speechrecognitionview/proguard-rules.pro b/speechrecognitionview/proguard-rules.pro
new file mode 100644
index 0000000000000000000000000000000000000000..f7666e47561d514b2a76d5a7dfbb43ede86da92a
--- /dev/null
+++ b/speechrecognitionview/proguard-rules.pro
@@ -0,0 +1 @@
+# config module specific ProGuard rules here.
\ No newline at end of file
diff --git a/speechrecognitionview/src/main/AndroidManifest.xml b/speechrecognitionview/src/main/AndroidManifest.xml
deleted file mode 100644
index c6e595a3fb3484749bb709999188667db1297245..0000000000000000000000000000000000000000
--- a/speechrecognitionview/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/speechrecognitionview/src/main/config.json b/speechrecognitionview/src/main/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..76db30ccdce5bfb9bc6e8498dadb3cd4e7372208
--- /dev/null
+++ b/speechrecognitionview/src/main/config.json
@@ -0,0 +1,37 @@
+{
+ "app": {
+ "bundleName": "com.github.zagum.speechrecognitionview.sample",
+ "vendor": "github",
+ "version": {
+ "code": 1000000,
+ "name": "1.0.0"
+ }
+ },
+ "deviceConfig": {
+ },
+ "module": {
+ "package": "com.github.zagum.speechrecognitionview",
+ "deviceType": [
+ "phone"
+ ],
+ "reqPermissions": [
+ {
+ "name": "ohos.permission.MICROPHONE"
+ },
+ {
+ "name": "ohos.permission.READ_MEDIA"
+ },
+ {
+ "name": "ohos.permission.WRITE_MEDIA"
+ },
+ {
+ "name": "ohos.permission.RECORD_AUDIO"
+ }
+ ],
+ "distro": {
+ "deliveryWithInstall": true,
+ "moduleName": "speechrecognitionview",
+ "moduleType": "har"
+ }
+ }
+}
\ No newline at end of file
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionBar.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionBar.java
index a6227ce790273fb65e0ea455fa1cc546b9d54cc6..40fd2bed59b9f933196d731c8f151969371fecbf 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionBar.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionBar.java
@@ -16,7 +16,7 @@
package com.github.zagum.speechrecognitionview;
-import android.graphics.RectF;
+import ohos.agp.utils.RectFloat;
public class RecognitionBar {
@@ -28,7 +28,7 @@ public class RecognitionBar {
private final int maxHeight;
private final int startX;
private final int startY;
- final private RectF rect;
+ final private RectFloat rect;
public RecognitionBar(int x, int y, int height, int maxHeight, int radius) {
this.x = x;
@@ -38,14 +38,14 @@ public class RecognitionBar {
this.startY = y;
this.height = height;
this.maxHeight = maxHeight;
- this.rect = new RectF(x - radius,
+ this.rect = new RectFloat(x - radius,
y - height / 2,
x + radius,
y + height / 2);
}
public void update() {
- rect.set(x - radius,
+ rect.modify(x - radius,
y - height / 2,
x + radius,
y + height / 2);
@@ -87,7 +87,7 @@ public class RecognitionBar {
return startY;
}
- public RectF getRect() {
+ public RectFloat getRect() {
return rect;
}
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionProgressView.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionProgressView.java
index c1893d923722bd5c0c2a02e53ee4e018accf27aa..a377fb9fda4cba0867340927ab7a98ca7169beda 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionProgressView.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/RecognitionProgressView.java
@@ -16,378 +16,699 @@
package com.github.zagum.speechrecognitionview;
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.os.Bundle;
-import android.speech.RecognitionListener;
-import android.speech.SpeechRecognizer;
-import android.util.AttributeSet;
-import android.view.View;
+import com.alibaba.fastjson.JSONObject;
import com.github.zagum.speechrecognitionview.animators.BarParamsAnimator;
import com.github.zagum.speechrecognitionview.animators.IdleAnimator;
import com.github.zagum.speechrecognitionview.animators.RmsAnimator;
import com.github.zagum.speechrecognitionview.animators.RotatingAnimator;
import com.github.zagum.speechrecognitionview.animators.TransformAnimator;
+import com.github.zagum.speechrecognitionview.util.DensityUtils;
+import ohos.agp.components.Attr;
+import ohos.agp.components.AttrSet;
+import ohos.agp.components.Component;
+import ohos.agp.components.ComponentContainer;
+import ohos.agp.render.Canvas;
+import ohos.agp.render.Paint;
+import ohos.agp.utils.Color;
+import ohos.ai.asr.AsrClient;
+import ohos.ai.asr.AsrIntent;
+import ohos.ai.asr.AsrListener;
+import ohos.ai.asr.util.AsrResultKey;
+import ohos.app.Context;
+import ohos.media.audio.AudioCapturer;
+import ohos.media.audio.AudioCapturerInfo;
+import ohos.media.audio.AudioStreamInfo;
+import ohos.utils.PacMap;
+
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+public class RecognitionProgressView extends ComponentContainer implements Component.DrawTask, ComponentContainer.ArrangeListener, AsrListener {
+
+ // RecognitionListener
+ public static final int BARS_COUNT = 5;
+
+ private static final int CIRCLE_RADIUS_DP = 5;
+ private static final int CIRCLE_SPACING_DP = 11;
+ private static final int ROTATION_RADIUS_DP = 25;
+ private static final int IDLE_FLOATING_AMPLITUDE_DP = 3;
+
+ private static final int[] DEFAULT_BARS_HEIGHT_DP = {60, 46, 70, 54, 64};
+
+ private static final float MDPI_DENSITY = 1.5f;
+
+ private final List recognitionBars = new ArrayList<>();
+ private Paint paint;
+ private BarParamsAnimator animator;
+
+ private int radius;
+ private int spacing;
+ private int rotationRadius;
+ private int amplitude;
+
+ private float density;
+
+ private boolean isSpeaking;
+ private boolean animating;
+ //todo
+ private AsrClient speechRecognizer;
+ private AsrListener recognitionListener;
+
+ private int barColor = -1;
+ private int[] barColors;
+ private int[] barMaxHeights;
+
+ private ThreadPoolExecutor poolExecutor;
+ private static final int POOL_SIZE = 3;
+ private static final int ALIVE_TIME = 3;
+ private static final int CAPACITY = 6;
+ private AudioCapturer audioCapturer;
+ private static final int SAMPLE_RATE = 16000;
+
+ private final static String TAG = "MainThisClass->";
+
+ private static final Map COMMAND_MAP = new HashMap<>();
+ private static final int VAD_END_WAIT_MS = 2000;
+ private static final int VAD_FRONT_WAIT_MS = 4800;
+ private static final int TIMEOUT_DURATION = 20000;
+ private boolean isRecord = false;
+ private static final int BYTES_LENGTH = 1280;
+
+ static {
+ COMMAND_MAP.put("拍照", true);
+ COMMAND_MAP.put("茄子", true);
+ }
+
+ public RecognitionProgressView(Context context) {
+ super(context);
+ init(context);
+ }
+
+ public RecognitionProgressView(Context context, AttrSet attrs) {
+ super(context, attrs);
+ init(context);
+ }
+
+ public RecognitionProgressView(Context context, AttrSet attrs, String defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ init(context);
+ }
+
+ /**
+ * Set SpeechRecognizer which is view animated with
+ *
+ * @param recognizer recognizer
+ */
+ public void setSpeechRecognizer(AsrClient recognizer) {
+ initAudioCapturer();
+ if(null!=speechRecognizer){
+ speechRecognizer.stopListening();
+ speechRecognizer.destroy();
+ speechRecognizer = null;
+ }
+ speechRecognizer = recognizer;
+ speechRecognizer.init(setInitIntent(), this);
+
+ // Initializes asr.
+// if (asrClient != null) {
+// asrClient.init(setInitIntent(), asrListener);
+// }
+ }
+
+ /**
+ * Set RecognitionListener to receive callbacks from {@link AsrListener}
+ *
+ * @param listener listener
+ */
+ public void setRecognitionListener(AsrListener listener) {
+ recognitionListener = listener;
+ }
+
+ /**
+ * Starts animating view
+ */
+ public void play() {
+ startIdleInterpolation();
+ animating = true;
+ }
+
+ public void play(int type) {
+ if (type == 1) {
+ startRmsInterpolation();
+ } else {
+ startTransformInterpolation();
+ }
+ }
+
+ /**
+ * Stops animating view
+ */
+ public void stop() {
+ if (animator != null) {
+ animator.stop();
+ animator = null;
+ }
+ animating = false;
+ resetBars();
+ }
+
+ /**
+ * Set one color to all bars in view
+ *
+ * @param color color
+ */
+ public void setSingleColor(int color) {
+ barColor = color;
+ }
+
+ /**
+ * Set different colors to bars in view
+ *
+ * @param colors - array with size = {@link #BARS_COUNT}
+ */
+ public void setColors(int[] colors) {
+ if (colors == null) return;
+
+ barColors = new int[BARS_COUNT];
+ if (colors.length < BARS_COUNT) {
+ System.arraycopy(colors, 0, barColors, 0, colors.length);
+ for (int i = colors.length; i < BARS_COUNT; i++) {
+ barColors[i] = colors[0];
+ }
+ } else {
+ System.arraycopy(colors, 0, barColors, 0, BARS_COUNT);
+ }
+ }
+
+ /**
+ * Set sizes of bars in view
+ *
+ * @param heights - array with size = {@link #BARS_COUNT},
+ * if not set uses default bars heights
+ */
+ public void setBarMaxHeightsInDp(int[] heights) {
+ if (heights == null) return;
+
+ barMaxHeights = new int[BARS_COUNT];
+ if (heights.length < BARS_COUNT) {
+ System.arraycopy(heights, 0, barMaxHeights, 0, heights.length);
+ for (int i = heights.length; i < BARS_COUNT; i++) {
+ barMaxHeights[i] = heights[0];
+ }
+ } else {
+ System.arraycopy(heights, 0, barMaxHeights, 0, BARS_COUNT);
+ }
+ }
+
+ /**
+ * Set radius of circle
+ *
+ * @param radius - Default value = {@link #CIRCLE_RADIUS_DP}
+ */
+ public void setCircleRadiusInDp(int radius) {
+ this.radius = (int) (radius * density);
+ }
+
+ /**
+ * Set spacing between circles
+ *
+ * @param spacing - Default value = {@link #CIRCLE_SPACING_DP}
+ */
+ public void setSpacingInDp(int spacing) {
+ this.spacing = (int) (spacing * density);
+ }
+
+ /**
+ * Set idle animation amplitude
+ *
+ * @param amplitude - Default value = {@link #IDLE_FLOATING_AMPLITUDE_DP}
+ */
+ public void setIdleStateAmplitudeInDp(int amplitude) {
+ this.amplitude = (int) (amplitude * density);
+ }
+
+ /**
+ * Set rotation animation radius
+ *
+ * @param radius - Default value = {@link #ROTATION_RADIUS_DP}
+ */
+ public void setRotationRadiusInDp(int radius) {
+ this.rotationRadius = (int) (radius * density);
+ }
+
+ private void init(Context context) {
+ paint = new Paint();
+ paint.setAntiAlias(true);
+ paint.setColor(Color.GRAY);
+ density = DensityUtils.getDeviceAttr(context).getAttributes().densityPixels;
+
+ radius = (int) (CIRCLE_RADIUS_DP * density);
+ spacing = (int) (CIRCLE_SPACING_DP * density);
+ rotationRadius = (int) (ROTATION_RADIUS_DP * density);
+ amplitude = (int) (IDLE_FLOATING_AMPLITUDE_DP * density);
+
+ if (density <= MDPI_DENSITY) {
+ amplitude *= 2;
+ }
+ addDrawTask(this);
+ setArrangeListener(this::onArrange);
+ }
+
+
+ private void initBars() {
+ final List heights = initBarHeights();
+ int firstCirclePosition = getEstimatedWidth() / 2 -
+ 2 * spacing -
+ 4 * radius;
+ for (int i = 0; i < BARS_COUNT; i++) {
+ int x = firstCirclePosition + (2 * radius + spacing) * i;
+ RecognitionBar bar = new RecognitionBar(x, getEstimatedHeight() / 2, 2 * radius, heights.get(i), radius);
+ recognitionBars.add(bar);
+ }
+ }
+
+ private List initBarHeights() {
+ final List barHeights = new ArrayList<>();
+ if (barMaxHeights == null) {
+ for (int i = 0; i < BARS_COUNT; i++) {
+ barHeights.add((int) (DEFAULT_BARS_HEIGHT_DP[i] * density));
+ }
+ } else {
+ for (int i = 0; i < BARS_COUNT; i++) {
+ barHeights.add((int) (barMaxHeights[i] * density));
+ }
+ }
+ return barHeights;
+ }
+
+ private void resetBars() {
+ for (RecognitionBar bar : recognitionBars) {
+ bar.setX(bar.getStartX());
+ bar.setY(bar.getStartY());
+ bar.setHeight(radius * 2);
+ bar.update();
+ }
+ }
+
+ private void startIdleInterpolation() {
+ animator = new IdleAnimator(recognitionBars, amplitude);
+ animator.start();
+ }
+
+ private void startRmsInterpolation() {
+ resetBars();
+ animator = new RmsAnimator(recognitionBars);
+ animator.start();
+ }
+
+ private void startTransformInterpolation() {
+ resetBars();
+ animator = new TransformAnimator(recognitionBars, getWidth() / 2, getHeight() / 2, rotationRadius);
+ animator.start();
+ ((TransformAnimator) animator).setOnInterpolationFinishedListener(new TransformAnimator.OnInterpolationFinishedListener() {
+ @Override
+ public void onFinished() {
+ startRotateInterpolation();
+ }
+ });
+ }
+
+ private void startRotateInterpolation() {
+ animator = new RotatingAnimator(recognitionBars, getWidth() / 2, getHeight() / 2);
+ animator.start();
+ }
+
+
+ @Override
+ public void onDraw(Component component, Canvas canvas) {
+ System.out.println("xxxyyy--->" + "onDraw");
+
+ if (recognitionBars.isEmpty()) {
+ System.out.println("xxxyyy--->" + "isEmpty");
+
+ return;
+ }
+ System.out.println("xxxyyy--->" + "return>>>" + animating);
+
+ if (animating) {
+ animator.animate();
+ }
+
+ for (int i = 0; i < recognitionBars.size(); i++) {
+ System.out.println("xxxyyy--->" + "i>>>" + i);
+
+ RecognitionBar bar = recognitionBars.get(i);
+ if (barColors != null) {
+ paint.setColor(new Color(barColors[i]));
+ } else if (barColor != -1) {
+ paint.setColor(new Color(barColor));
+ }
+ canvas.drawRoundRect(bar.getRect(), radius, radius, paint);
+ }
+ System.out.println("xxxyyy--->" + "i>animating>>" + animating);
+
+ if (animating) {
+ getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
+ @Override
+ public void run() {
+ invalidate();
+ }
+ });
+ }
+
+ }
+
+ //12)参数l表示相对于父view的Left位置;
+// 3)参数t表示相对于父view的Top位置;
+// 4)参数r表示相对于父view的Right位置;
+// 5)参数b表示相对于父view的Bottom位置。.
+ private int left;
+ private int top;
+ private int right;
+ private int bottom;
+ private boolean isChanged = false;
+
+ @Override
+ public boolean onArrange(int i, int i1, int i2, int i3) {
+
+ if (left == i && i1 == top && i2 == right && i3 == bottom) {
+ isChanged = false;
+ } else {
+ isChanged = true;
+ }
+
+ left = i;
+ top = i1;
+ right = i2;
+ bottom = i3;
+ System.out.println("xxxyyy--->" + "onarrent");
+ if (recognitionBars.isEmpty()) {
+ initBars();
+ } else if (isChanged) {
+ recognitionBars.clear();
+ initBars();
+ }
+ return true;
+ }
+
+ // @Override
+// protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+// super.onLayout(changed, left, top, right, bottom);
+// if (recognitionBars.isEmpty()) {
+// initBars();
+// } else if (changed) {
+// recognitionBars.clear();
+// initBars();
+// }
+// }
+ //todo
+// @Override
+// public void onReadyForSpeech(Bundle params) {
+// if (recognitionListener != null) {
+// recognitionListener.onReadyForSpeech(params);
+// }
+// }
+ @Override
+ public void onInit(PacMap pacMap) {
+ openAudio();
+ System.out.println(TAG + "======onInit======");
+ if (recognitionListener != null) {
+ recognitionListener.onInit(pacMap);
+ }
+ }
+//
+// @Override
+// public void onBeginningOfSpeech() {
+// if (recognitionListener != null) {
+// recognitionListener.onBeginningOfSpeech();
+// }
+// isSpeaking = true;
+// }
+
+ @Override
+ public void onBeginningOfSpeech() {
+ System.out.println(TAG + "======onBeginningOfSpeech======");
+
+ if (recognitionListener != null) {
+ recognitionListener.onBeginningOfSpeech();
+ }
+ isSpeaking = true;
+ }
+//
+// @Override
+// public void onRmsChanged(float rmsdB) {
+// if (recognitionListener != null) {
+// recognitionListener.onRmsChanged(rmsdB);
+// }
+// if (animator == null || rmsdB < 1f) {
+// return;
+// }
+// if (!(animator instanceof RmsAnimator) && isSpeaking) {
+// startRmsInterpolation();
+// }
+// if (animator instanceof RmsAnimator) {
+// ((RmsAnimator) animator).onRmsChanged(rmsdB);
+// }
+// }
+
+ @Override
+ public void onRmsChanged(float rmsdB) {
+ System.out.println(TAG + "======onRmsChanged======");
+
+ if (recognitionListener != null) {
+ recognitionListener.onRmsChanged(rmsdB);
+ }
+ if (animator == null || rmsdB < 1f) {
+ return;
+ }
+ if (!(animator instanceof RmsAnimator) && isSpeaking) {
+ startRmsInterpolation();
+ }
+ if (animator instanceof RmsAnimator) {
+ ((RmsAnimator) animator).onRmsChanged(rmsdB);
+ }
+ }
+
+ //
+// @Override
+// public void onBufferReceived(byte[] buffer) {
+// if (recognitionListener != null) {
+// recognitionListener.onBufferReceived(buffer);
+// }
+// }
+ @Override
+ public void onBufferReceived(byte[] bytes) {
+ if (recognitionListener != null) {
+ recognitionListener.onBufferReceived(bytes);
+ }
+ }
+
+ //
+// @Override
+// public void onEndOfSpeech() {
+// if (recognitionListener != null) {
+// recognitionListener.onEndOfSpeech();
+// }
+// isSpeaking = false;
+// startTransformInterpolation();
+// }
+ @Override
+ public void onEndOfSpeech() {
+ if (recognitionListener != null) {
+ recognitionListener.onEndOfSpeech();
+ }
+ isSpeaking = false;
+ startTransformInterpolation();
+ }
+
+ //
+// @Override
+// public void onError(int error) {
+// if (recognitionListener != null) {
+// recognitionListener.onError(error);
+// }
+// }
+ @Override
+ public void onError(int error) {
+ System.out.println(TAG + "======onError:"+error);
+// if(error == 5 ) {
+// setSpeechRecognizer(speechRecognizer);
+// }
+ if (recognitionListener != null) {
+ recognitionListener.onError(error);
+ }
+ isSpeaking = false;
+ if(error != 5 ) {
+ startTransformInterpolation();
+ }
+ }
+
+ //
+// @Override
+// public void onResults(Bundle results) {
+// if (recognitionListener != null) {
+// recognitionListener.onResults(results);
+// }
+// }
+ @Override
+ public void onResults(PacMap pacMap) {
+ speechRecognizer.startListening(setStartIntent());
+ if (recognitionListener != null) {
+ recognitionListener.onResults(pacMap);
+ }
+ System.out.println(TAG + "======onResults:");
+
+ }
+//
+// @Override
+// public void onPartialResults(Bundle partialResults) {
+// if (recognitionListener != null) {
+// recognitionListener.onPartialResults(partialResults);
+// }
+// }
+//
+
+ @Override
+ public void onIntermediateResults(PacMap pacMap) {
+ System.out.println(TAG + "======onIntermediateResults:");
+// boolean recognizeResult = recognizeWords(result);
+
+// if (recognizeResult && !recognizeOver) {
+// recognizeOver = true;
+//// takePicture(new Component(getContext()));
+// speechRecognizer.stopListening();
+// }
+ if (recognitionListener != null) {
+ recognitionListener.onIntermediateResults(pacMap);
+ }
+ }
+
+ @Override
+ public void onEnd() {
+ System.out.println(TAG + "======onEnd:");
+ speechRecognizer.stopListening();
+ speechRecognizer.startListening(setStartIntent());
+ }
+
+ // @Override
+// public void onEvent(int eventType, Bundle params) {
+// if (recognitionListener != null) {
+// recognitionListener.onEvent(eventType, params);
+// }
+// }
+ @Override
+ public void onEvent(int eventType, PacMap pacMap) {
+ if (recognitionListener != null) {
+ recognitionListener.onEvent(eventType, pacMap);
+ }
+ }
+
+ @Override
+ public void onAudioStart() {
+
+ }
+
+ @Override
+ public void onAudioEnd() {
+
+ }
+
+
+ private void initAudioCapturer() {
+ System.out.println(TAG + "initAudioCapturer");
+
+ poolExecutor =
+ new ThreadPoolExecutor(
+ POOL_SIZE,
+ POOL_SIZE,
+ ALIVE_TIME,
+ TimeUnit.SECONDS,
+ new LinkedBlockingQueue<>(CAPACITY),
+ new ThreadPoolExecutor.DiscardOldestPolicy());
+
+ AudioStreamInfo audioStreamInfo =
+ new AudioStreamInfo.Builder()
+ .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT)
+ .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_IN_MONO)
+ .sampleRate(SAMPLE_RATE)
+ .build();
+//
+ AudioCapturerInfo audioCapturerInfo = new AudioCapturerInfo.Builder().audioStreamInfo(audioStreamInfo).build();
+//
+ audioCapturer = new AudioCapturer(audioCapturerInfo);
+ }
+
+
+ private void openAudio() {
+ System.out.println(TAG + "openAudio");
+
+ if (!isRecord) {
+ System.out.println(TAG + "isRecord");
+
+ speechRecognizer.startListening(setStartIntent());
+ isRecord = true;
+ poolExecutor.submit(new AudioCaptureRunnable());
+ }
+ }
+
+ /**
+ * Obtains PCM audio streams and sends them to the ASR engine during recording.
+ *
+ * @since 2021-03-08
+ */
+ private class AudioCaptureRunnable implements Runnable {
+ @Override
+ public void run() {
+ byte[] buffers = new byte[BYTES_LENGTH];
+ audioCapturer.start();
+ while (isRecord) {
+ int ret = audioCapturer.read(buffers, 0, BYTES_LENGTH);
+ if (ret <= 0) {
+// HiLog.error(TAG, "======Error read data");
+ } else {
+ speechRecognizer.writePcm(buffers, BYTES_LENGTH);
+ }
+ }
+ }
+ }
+
+ private boolean recognizeWords(String result) {
+ JSONObject jsonObject = JSONObject.parseObject(result);
+ JSONObject resultObject = new JSONObject();
+ if (jsonObject.getJSONArray("result").get(0) instanceof JSONObject) {
+ resultObject = (JSONObject) jsonObject.getJSONArray("result").get(0);
+ }
+ String resultWord = resultObject.getString("ori_word").replace(" ", "");
+ boolean command = COMMAND_MAP.getOrDefault(resultWord, false);
+ System.out.println(TAG + "======" + resultWord + "===" + command);
+ return command;
+ }
+
+ private AsrIntent setInitIntent() {
+ AsrIntent initIntent = new AsrIntent();
+ initIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM);
+ initIntent.setEngineType(AsrIntent.AsrEngineType.ASR_ENGINE_TYPE_LOCAL);
+ return initIntent;
+ }
+
+ private AsrIntent setStartIntent() {
+ AsrIntent asrIntent = new AsrIntent();
+ asrIntent.setVadEndWaitMs(VAD_END_WAIT_MS);
+ asrIntent.setVadFrontWaitMs(VAD_FRONT_WAIT_MS);
+ asrIntent.setTimeoutThresholdMs(TIMEOUT_DURATION);
+ return asrIntent;
+ }
+
-public class RecognitionProgressView extends View implements RecognitionListener {
-
- public static final int BARS_COUNT = 5;
-
- private static final int CIRCLE_RADIUS_DP = 5;
- private static final int CIRCLE_SPACING_DP = 11;
- private static final int ROTATION_RADIUS_DP = 25;
- private static final int IDLE_FLOATING_AMPLITUDE_DP = 3;
-
- private static final int[] DEFAULT_BARS_HEIGHT_DP = { 60, 46, 70, 54, 64 };
-
- private static final float MDPI_DENSITY = 1.5f;
-
- private final List recognitionBars = new ArrayList<>();
- private Paint paint;
- private BarParamsAnimator animator;
-
- private int radius;
- private int spacing;
- private int rotationRadius;
- private int amplitude;
-
- private float density;
-
- private boolean isSpeaking;
- private boolean animating;
-
- private SpeechRecognizer speechRecognizer;
- private RecognitionListener recognitionListener;
- private int barColor = -1;
- private int[] barColors;
- private int[] barMaxHeights;
-
- public RecognitionProgressView(Context context) {
- super(context);
- init();
- }
-
- public RecognitionProgressView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
-
- public RecognitionProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- init();
- }
-
- /**
- * Set SpeechRecognizer which is view animated with
- */
- public void setSpeechRecognizer(SpeechRecognizer recognizer) {
- speechRecognizer = recognizer;
- speechRecognizer.setRecognitionListener(this);
- }
-
- /**
- * Set RecognitionListener to receive callbacks from {@link SpeechRecognizer}
- */
- public void setRecognitionListener(RecognitionListener listener) {
- recognitionListener = listener;
- }
-
- /**
- * Starts animating view
- */
- public void play() {
- startIdleInterpolation();
- animating = true;
- }
-
- /**
- * Stops animating view
- */
- public void stop() {
- if (animator != null) {
- animator.stop();
- animator = null;
- }
- animating = false;
- resetBars();
- }
-
- /**
- * Set one color to all bars in view
- */
- public void setSingleColor(int color) {
- barColor = color;
- }
-
- /**
- * Set different colors to bars in view
- *
- * @param colors - array with size = {@link #BARS_COUNT}
- */
- public void setColors(int[] colors) {
- if (colors == null) return;
-
- barColors = new int[BARS_COUNT];
- if (colors.length < BARS_COUNT) {
- System.arraycopy(colors, 0, barColors, 0, colors.length);
- for (int i = colors.length; i < BARS_COUNT; i++) {
- barColors[i] = colors[0];
- }
- } else {
- System.arraycopy(colors, 0, barColors, 0, BARS_COUNT);
- }
- }
-
- /**
- * Set sizes of bars in view
- *
- * @param heights - array with size = {@link #BARS_COUNT},
- * if not set uses default bars heights
- */
- public void setBarMaxHeightsInDp(int[] heights) {
- if (heights == null) return;
-
- barMaxHeights = new int[BARS_COUNT];
- if (heights.length < BARS_COUNT) {
- System.arraycopy(heights, 0, barMaxHeights, 0, heights.length);
- for (int i = heights.length; i < BARS_COUNT; i++) {
- barMaxHeights[i] = heights[0];
- }
- } else {
- System.arraycopy(heights, 0, barMaxHeights, 0, BARS_COUNT);
- }
- }
-
- /**
- * Set radius of circle
- *
- * @param radius - Default value = {@link #CIRCLE_RADIUS_DP}
- */
- public void setCircleRadiusInDp(int radius) {
- this.radius = (int) (radius * density);
- }
-
- /**
- * Set spacing between circles
- *
- * @param spacing - Default value = {@link #CIRCLE_SPACING_DP}
- */
- public void setSpacingInDp(int spacing) {
- this.spacing = (int) (spacing * density);
- }
-
- /**
- * Set idle animation amplitude
- *
- * @param amplitude - Default value = {@link #IDLE_FLOATING_AMPLITUDE_DP}
- */
- public void setIdleStateAmplitudeInDp(int amplitude) {
- this.amplitude = (int) (amplitude * density);
- }
-
- /**
- * Set rotation animation radius
- *
- * @param radius - Default value = {@link #ROTATION_RADIUS_DP}
- */
- public void setRotationRadiusInDp(int radius) {
- this.rotationRadius = (int) (radius * density);
- }
-
- private void init() {
- paint = new Paint();
- paint.setFlags(Paint.ANTI_ALIAS_FLAG);
- paint.setColor(Color.GRAY);
-
- density = getResources().getDisplayMetrics().density;
-
- radius = (int) (CIRCLE_RADIUS_DP * density);
- spacing = (int) (CIRCLE_SPACING_DP * density);
- rotationRadius = (int) (ROTATION_RADIUS_DP * density);
- amplitude = (int) (IDLE_FLOATING_AMPLITUDE_DP * density);
-
- if (density <= MDPI_DENSITY) {
- amplitude *= 2;
- }
- }
-
- @Override
- protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
- super.onLayout(changed, left, top, right, bottom);
- if (recognitionBars.isEmpty()) {
- initBars();
- } else if (changed) {
- recognitionBars.clear();
- initBars();
- }
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
-
- if (recognitionBars.isEmpty()) {
- return;
- }
-
- if (animating) {
- animator.animate();
- }
-
- for (int i = 0; i < recognitionBars.size(); i++) {
- RecognitionBar bar = recognitionBars.get(i);
- if (barColors != null) {
- paint.setColor(barColors[i]);
- } else if (barColor != -1) {
- paint.setColor(barColor);
- }
- canvas.drawRoundRect(bar.getRect(), radius, radius, paint);
- }
-
- if (animating) {
- invalidate();
- }
- }
-
- private void initBars() {
- final List heights = initBarHeights();
- int firstCirclePosition = getMeasuredWidth() / 2 -
- 2 * spacing -
- 4 * radius;
- for (int i = 0; i < BARS_COUNT; i++) {
- int x = firstCirclePosition + (2 * radius + spacing) * i;
- RecognitionBar bar = new RecognitionBar(x, getMeasuredHeight() / 2, 2 * radius, heights.get(i), radius);
- recognitionBars.add(bar);
- }
- }
-
- private List initBarHeights() {
- final List barHeights = new ArrayList<>();
- if (barMaxHeights == null) {
- for (int i = 0; i < BARS_COUNT; i++) {
- barHeights.add((int) (DEFAULT_BARS_HEIGHT_DP[i] * density));
- }
- } else {
- for (int i = 0; i < BARS_COUNT; i++) {
- barHeights.add((int) (barMaxHeights[i] * density));
- }
- }
- return barHeights;
- }
-
- private void resetBars() {
- for (RecognitionBar bar : recognitionBars) {
- bar.setX(bar.getStartX());
- bar.setY(bar.getStartY());
- bar.setHeight(radius * 2);
- bar.update();
- }
- }
-
- private void startIdleInterpolation() {
- animator = new IdleAnimator(recognitionBars, amplitude);
- animator.start();
- }
-
- private void startRmsInterpolation() {
- resetBars();
- animator = new RmsAnimator(recognitionBars);
- animator.start();
- }
-
- private void startTransformInterpolation() {
- resetBars();
- animator = new TransformAnimator(recognitionBars, getWidth() / 2, getHeight() / 2, rotationRadius);
- animator.start();
- ((TransformAnimator) animator).setOnInterpolationFinishedListener(new TransformAnimator.OnInterpolationFinishedListener() {
- @Override
- public void onFinished() {
- startRotateInterpolation();
- }
- });
- }
-
- private void startRotateInterpolation() {
- animator = new RotatingAnimator(recognitionBars, getWidth() / 2, getHeight() / 2);
- animator.start();
- }
-
- @Override
- public void onReadyForSpeech(Bundle params) {
- if (recognitionListener != null) {
- recognitionListener.onReadyForSpeech(params);
- }
- }
-
- @Override
- public void onBeginningOfSpeech() {
- if (recognitionListener != null) {
- recognitionListener.onBeginningOfSpeech();
- }
- isSpeaking = true;
- }
-
- @Override
- public void onRmsChanged(float rmsdB) {
- if (recognitionListener != null) {
- recognitionListener.onRmsChanged(rmsdB);
- }
- if (animator == null || rmsdB < 1f) {
- return;
- }
- if (!(animator instanceof RmsAnimator) && isSpeaking) {
- startRmsInterpolation();
- }
- if (animator instanceof RmsAnimator) {
- ((RmsAnimator) animator).onRmsChanged(rmsdB);
- }
- }
-
- @Override
- public void onBufferReceived(byte[] buffer) {
- if (recognitionListener != null) {
- recognitionListener.onBufferReceived(buffer);
- }
- }
-
- @Override
- public void onEndOfSpeech() {
- if (recognitionListener != null) {
- recognitionListener.onEndOfSpeech();
- }
- isSpeaking = false;
- startTransformInterpolation();
- }
-
- @Override
- public void onError(int error) {
- if (recognitionListener != null) {
- recognitionListener.onError(error);
- }
- }
-
- @Override
- public void onResults(Bundle results) {
- if (recognitionListener != null) {
- recognitionListener.onResults(results);
- }
- }
-
- @Override
- public void onPartialResults(Bundle partialResults) {
- if (recognitionListener != null) {
- recognitionListener.onPartialResults(partialResults);
- }
- }
+//
+// @Override
+// protected void onDraw(Canvas canvas) {
+// super.onDraw(canvas);
+// }
- @Override
- public void onEvent(int eventType, Bundle params) {
- if (recognitionListener != null) {
- recognitionListener.onEvent(eventType, params);
- }
- }
}
\ No newline at end of file
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/adapters/RecognitionListenerAdapter.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/adapters/RecognitionListenerAdapter.java
index fa02488a3bf58a55dac48e541bbead1bbcf8c87b..d522910d11f8bc60b3e4b72ab3aeac7ae7473461 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/adapters/RecognitionListenerAdapter.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/adapters/RecognitionListenerAdapter.java
@@ -1,42 +1,67 @@
package com.github.zagum.speechrecognitionview.adapters;
-import android.os.Bundle;
-import android.speech.RecognitionListener;
-public abstract class RecognitionListenerAdapter implements RecognitionListener {
- @Override
- public void onReadyForSpeech(Bundle params) {
- }
+import ohos.ai.asr.AsrListener;
+import ohos.utils.PacMap;
- @Override
- public void onBeginningOfSpeech() {
- }
+public abstract class RecognitionListenerAdapter implements AsrListener {
+ @Override
+ public void onInit(PacMap pacMap) {
- @Override
- public void onRmsChanged(float rmsdB) {
- }
+ }
- @Override
- public void onBufferReceived(byte[] buffer) {
- }
+ @Override
+ public void onBeginningOfSpeech() {
- @Override
- public void onEndOfSpeech() {
- }
+ }
- @Override
- public void onError(int error) {
- }
+ @Override
+ public void onRmsChanged(float v) {
- @Override
- public void onResults(Bundle results) {
- }
+ }
- @Override
- public void onPartialResults(Bundle partialResults) {
- }
+ @Override
+ public void onBufferReceived(byte[] bytes) {
- @Override
- public void onEvent(int eventType, Bundle params) {
- }
+ }
+
+ @Override
+ public void onEndOfSpeech() {
+
+ }
+
+ @Override
+ public void onError(int i) {
+
+ }
+
+ @Override
+ public void onResults(PacMap pacMap) {
+
+ }
+
+ @Override
+ public void onIntermediateResults(PacMap pacMap) {
+
+ }
+
+ @Override
+ public void onEnd() {
+
+ }
+
+ @Override
+ public void onEvent(int i, PacMap pacMap) {
+
+ }
+
+ @Override
+ public void onAudioStart() {
+
+ }
+
+ @Override
+ public void onAudioEnd() {
+
+ }
}
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/BarRmsAnimator.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/BarRmsAnimator.java
index bb542c9230f71b1afbfbf0cd38f12225963ff179..81300b9f3a05d9aba7bb311f69b6579ed46717aa 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/BarRmsAnimator.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/BarRmsAnimator.java
@@ -16,12 +16,11 @@
package com.github.zagum.speechrecognitionview.animators;
-import android.view.animation.AccelerateInterpolator;
-import android.view.animation.DecelerateInterpolator;
-
import com.github.zagum.speechrecognitionview.RecognitionBar;
+import ohos.agp.animation.Animator;
+import ohos.agp.animation.AnimatorValue;
-import java.util.Random;
+import java.security.SecureRandom;
public class BarRmsAnimator implements BarParamsAnimator {
@@ -36,9 +35,11 @@ public class BarRmsAnimator implements BarParamsAnimator {
private long startTimestamp;
private boolean isPlaying;
private boolean isUpAnimation;
+ private SecureRandom secureRandom ;
public BarRmsAnimator(RecognitionBar bar) {
this.bar = bar;
+ secureRandom = new SecureRandom();
}
@Override
@@ -64,10 +65,10 @@ public class BarRmsAnimator implements BarParamsAnimator {
if (rmsdB < QUIT_RMSDB_MAX) {
newHeightPart = 0.2f;
} else if (rmsdB >= QUIT_RMSDB_MAX && rmsdB <= MEDIUM_RMSDB_MAX) {
- newHeightPart = 0.3f + new Random().nextFloat();
+ newHeightPart = 0.3f + secureRandom.nextFloat();
if (newHeightPart > 0.6f) newHeightPart = 0.6f;
} else {
- newHeightPart = 0.7f + new Random().nextFloat();
+ newHeightPart = 0.7f + secureRandom.nextFloat();
if (newHeightPart > 1f) newHeightPart = 1f;
}
@@ -107,8 +108,7 @@ public class BarRmsAnimator implements BarParamsAnimator {
float timePart = (float) delta / BAR_ANIMATION_UP_DURATION;
- AccelerateInterpolator interpolator = new AccelerateInterpolator();
- int height = minHeight + (int) (interpolator.getInterpolation(timePart) * (toHeight - minHeight));
+ int height = minHeight + (int) (getInterpolation(timePart) * (toHeight - minHeight));
if (height < bar.getHeight()) {
return;
@@ -127,15 +127,20 @@ public class BarRmsAnimator implements BarParamsAnimator {
startTimestamp = System.currentTimeMillis();
}
}
-
+ private float getInterpolation(float input) {
+ if (true) {
+ return input * input;
+ } else {
+ return (float)Math.pow(input, 2.0);
+ }
+ }
private void animateDown(long delta) {
+ //todo
int minHeight = bar.getRadius() * 2;
int fromHeight = (int) (bar.getMaxHeight() * toHeightPart);
float timePart = (float) delta / BAR_ANIMATION_DOWN_DURATION;
-
- DecelerateInterpolator interpolator = new DecelerateInterpolator();
- int height = minHeight + (int) ((1f - interpolator.getInterpolation(timePart)) * (fromHeight - minHeight));
+ int height = minHeight + (int) ((1f - getDInterpolation(timePart)) * (fromHeight - minHeight));
if (height > bar.getHeight()) {
return;
@@ -149,7 +154,15 @@ public class BarRmsAnimator implements BarParamsAnimator {
bar.setHeight(height);
bar.update();
}
-
+ public float getDInterpolation(float input) {
+ float result;
+ if (true) {
+ result = (float)(1.0f - (1.0f - input) * (1.0f - input));
+ } else {
+ result = (float)(1.0f - Math.pow((1.0f - input), 2 * 1.0f));
+ }
+ return result;
+ }
private void finish() {
bar.setHeight(bar.getRadius() * 2);
bar.update();
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/RotatingAnimator.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/RotatingAnimator.java
index 9dac989c9dac36366524342aee5e0f59a7adc194..790d9f9b74511bd9e9c71f4ffcdeae9e6b96358e 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/RotatingAnimator.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/RotatingAnimator.java
@@ -16,10 +16,11 @@
package com.github.zagum.speechrecognitionview.animators;
-import android.graphics.Point;
-import android.view.animation.AccelerateDecelerateInterpolator;
-
import com.github.zagum.speechrecognitionview.RecognitionBar;
+import ohos.agp.animation.Animator;
+import ohos.agp.animation.AnimatorProperty;
+import ohos.agp.animation.AnimatorValue;
+import ohos.agp.utils.Point;
import java.util.ArrayList;
import java.util.List;
@@ -62,6 +63,8 @@ public class RotatingAnimator implements BarParamsAnimator {
@Override
public void animate() {
+ System.out.println("animate--isPlaying>"+isPlaying);
+
if (!isPlaying) return;
long currTimestamp = System.currentTimeMillis();
@@ -75,48 +78,56 @@ public class RotatingAnimator implements BarParamsAnimator {
float angle = interpolatedTime * ROTATION_DEGREES;
- int i = 0;
- for (RecognitionBar bar : bars) {
+ System.out.println("barsize-->"+bars.size());
+ for (int j = 0;j 0 && delta > ACCELERATE_ROTATION_DURATION) {
- finalAngle += decelerate(delta, bars.size() - i);
- } else if (i > 0) {
- finalAngle += accelerate(delta, bars.size() - i);
+ if (j > 0 && delta > ACCELERATE_ROTATION_DURATION) {
+ System.out.println("finalAngle-->"+"ACCELERATE_ROTATION_DURATION)");
+
+ finalAngle += decelerate(delta, bars.size() - j);
+ System.out.println("finalAnglefinalAngle-->"+finalAngle);
+
+ } else if (j > 0) {
+ System.out.println("finalAngle-->"+"elsej");
+
+ finalAngle += accelerate(delta, bars.size() - j);
}
- rotate(bar, finalAngle, startPositions.get(i));
- i++;
+ rotate(bars.get(j), finalAngle, startPositions.get(j));
+
}
}
private float decelerate(long delta, int scale) {
long accelerationDelta = delta - ACCELERATE_ROTATION_DURATION;
- AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
- float interpolatedTime = interpolator.getInterpolation((float) accelerationDelta / DECELERATE_ROTATION_DURATION);
+ float interpolatedTime = getInterpolation((float) accelerationDelta / DECELERATE_ROTATION_DURATION);
float decelerationAngle = -interpolatedTime * (ACCELERATION_ROTATION_DEGREES * scale);
+ System.out.println("decelerate---->"+interpolatedTime + "--->"+decelerationAngle);
return ACCELERATION_ROTATION_DEGREES * scale + decelerationAngle;
}
private float accelerate(long delta, int scale) {
long accelerationDelta = delta;
- AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
- float interpolatedTime = interpolator.getInterpolation((float) accelerationDelta / ACCELERATE_ROTATION_DURATION);
+ float interpolatedTime = getInterpolation((float) accelerationDelta / ACCELERATE_ROTATION_DURATION);
float accelerationAngle = interpolatedTime * (ACCELERATION_ROTATION_DEGREES * scale);
+ System.out.println("accelerate---->"+interpolatedTime + "--->"+accelerationAngle);
+
return accelerationAngle;
}
+ private float getInterpolation(float input) {
+ return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
+ }
+
- /**
- * X = x0 + (x - x0) * cos(a) - (y - y0) * sin(a);
- * Y = y0 + (y - y0) * cos(a) + (x - x0) * sin(a);
- */
private void rotate(RecognitionBar bar, double degrees, Point startPosition) {
double angle = Math.toRadians(degrees);
- int x = centerX + (int) ((startPosition.x - centerX) * Math.cos(angle) -
- (startPosition.y - centerY) * Math.sin(angle));
+ int x = centerX + (int) ((startPosition.getPointX() - centerX) * Math.cos(angle) -
+ (startPosition.getPointY() - centerY) * Math.sin(angle));
- int y = centerY + (int) ((startPosition.x - centerX) * Math.sin(angle) +
- (startPosition.y - centerY) * Math.cos(angle));
+ int y = centerY + (int) ((startPosition.getPointX() - centerX) * Math.sin(angle) +
+ (startPosition.getPointY() - centerY) * Math.cos(angle));
bar.setX(x);
bar.setY(y);
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/TransformAnimator.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/TransformAnimator.java
index 9a6e353c24d5e8ebc0de65824b9f53b96de21af7..977d18fdc33f42147d6317fd54d265f5936f5d2e 100644
--- a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/TransformAnimator.java
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/animators/TransformAnimator.java
@@ -16,10 +16,9 @@
package com.github.zagum.speechrecognitionview.animators;
-import android.graphics.Point;
-
import com.github.zagum.speechrecognitionview.RecognitionBar;
import com.github.zagum.speechrecognitionview.RecognitionProgressView;
+import ohos.agp.utils.Point;
import java.util.ArrayList;
import java.util.List;
@@ -70,18 +69,22 @@ public class TransformAnimator implements BarParamsAnimator {
if (delta > DURATION) {
delta = DURATION;
}
+ try {
+ for (int i = 0; i < bars.size(); i++) {
+ RecognitionBar bar = bars.get(i);
- for (int i = 0; i < bars.size(); i++) {
- RecognitionBar bar = bars.get(i);
+ int x = bar.getStartX() + (int) ((finalPositions.get(i).getPointX() - bar.getStartX()) * ((float) delta / DURATION));
+ int y = bar.getStartY() + (int) ((finalPositions.get(i).getPointY() - bar.getStartY()) * ((float) delta / DURATION));
- int x = bar.getStartX() + (int) ((finalPositions.get(i).x - bar.getStartX()) * ((float) delta / DURATION));
- int y = bar.getStartY() + (int) ((finalPositions.get(i).y - bar.getStartY()) * ((float) delta / DURATION));
+ bar.setX(x);
+ bar.setY(y);
+ bar.update();
+ }
- bar.setX(x);
- bar.setY(y);
- bar.update();
- }
+ }catch (Exception e){
+ e.fillInStackTrace();
+ }
if (delta == DURATION) {
stop();
@@ -89,9 +92,7 @@ public class TransformAnimator implements BarParamsAnimator {
}
private void initFinalPositions() {
- Point startPoint = new Point();
- startPoint.x = centerX;
- startPoint.y = centerY - radius;
+ Point startPoint = new Point(centerX,centerY - radius);
for (int i = 0; i < RecognitionProgressView.BARS_COUNT; i++) {
Point point = new Point(startPoint);
rotate((360d / RecognitionProgressView.BARS_COUNT) * i, point);
@@ -99,22 +100,18 @@ public class TransformAnimator implements BarParamsAnimator {
}
}
- /**
- * X = x0 + (x - x0) * cos(a) - (y - y0) * sin(a);
- * Y = y0 + (y - y0) * cos(a) + (x - x0) * sin(a);
- **/
+
private void rotate(double degrees, Point point) {
double angle = Math.toRadians(degrees);
- int x = centerX + (int) ((point.x - centerX) * Math.cos(angle) -
- (point.y - centerY) * Math.sin(angle));
+ int x = centerX + (int) ((point.getPointX() - centerX) * Math.cos(angle) -
+ (point.getPointY() - centerY) * Math.sin(angle));
- int y = centerY + (int) ((point.x - centerX) * Math.sin(angle) +
- (point.y - centerY) * Math.cos(angle));
+ int y = centerY + (int) ((point.getPointX() - centerX) * Math.sin(angle) +
+ (point.getPointY() - centerY) * Math.cos(angle));
- point.x = x;
- point.y = y;
+ point.modify(x,y);
}
public void setOnInterpolationFinishedListener(OnInterpolationFinishedListener listener) {
diff --git a/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/util/DensityUtils.java b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/util/DensityUtils.java
new file mode 100644
index 0000000000000000000000000000000000000000..de556e3aa0fdb3e02ef15e7debbcbe7da7adac64
--- /dev/null
+++ b/speechrecognitionview/src/main/java/com/github/zagum/speechrecognitionview/util/DensityUtils.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2021 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.github.zagum.speechrecognitionview.util;
+
+import ohos.agp.colors.RgbColor;
+import ohos.agp.components.AttrHelper;
+import ohos.agp.text.Font;
+import ohos.agp.utils.Color;
+import ohos.agp.window.service.Display;
+import ohos.agp.window.service.DisplayManager;
+import ohos.app.Context;
+
+import java.io.File;
+import java.util.Optional;
+
+import static ohos.agp.components.AttrHelper.getDensity;
+
+/**
+ * DensityUtils
+ *
+ * @since 2021-05-14
+ */
+public class DensityUtils {
+ /**
+ * fp 转 Px
+ *
+ * @param context context
+ * @param fp fp
+ * @return px
+ */
+ public static int fpToPx(final Context context, final float fp) {
+ return AttrHelper.fp2px(fp, getDensity(context));
+ }
+
+ /**
+ * px 转 Fp
+ *
+ * @param context context
+ * @param px px
+ * @return fp
+ */
+ public static int pxToFp(final Context context, final float px) {
+ return Math.round(px * getDensity(context));
+ }
+
+ /**
+ * 通过文件返回字体
+ *
+ * @param path path
+ * @return Font
+ */
+ public static Font font(File path) {
+ Font.Builder font = new Font.Builder(path);
+ return font.build();
+ }
+
+ /**
+ * 通过name返回字体
+ *
+ * @param name name
+ * @return font
+ */
+ public static Font font(String name) {
+ Font.Builder font = new Font.Builder(name);
+ return font.build();
+ }
+
+ /**
+ * 获取当前设备属性
+ *
+ * @param context context
+ * @return Attr
+ */
+ public static Display getDeviceAttr(Context context) {
+ Optional optional = DisplayManager.getInstance().getDefaultDisplay(context);
+ return optional.get();
+ }
+
+ /**
+ * 屏幕宽
+ *
+ * @param context context
+ * @return Width
+ */
+ public static int getDisplayWidth(Context context) {
+ return getDeviceAttr(context).getRealAttributes().width;
+ }
+
+ /**
+ * 屏幕高
+ *
+ * @param context context
+ * @return Height
+ */
+ public static int getDisplayHeight(Context context) {
+ return getDeviceAttr(context).getRealAttributes().height;
+ }
+
+ /**
+ * rgb颜色
+ *
+ * @param color color
+ * @return RgbColor
+ */
+ private RgbColor getRgbColor(Color color) {
+ return RgbColor.fromArgbInt(color.getValue());
+ }
+}
\ No newline at end of file
diff --git a/speechrecognitionview/src/main/resources/base/element/string.json b/speechrecognitionview/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..d7d07d5a4038e6f3b2d5f384b6a3503e2350e12f
--- /dev/null
+++ b/speechrecognitionview/src/main/resources/base/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "speechrecognitionview_library",
+ "value": "speechrecognitionview_library"
+ }
+ ]
+}
diff --git a/speechrecognitionview/src/test/java/com/github/zagum/speechrecognitionview/ExampleTest.java b/speechrecognitionview/src/test/java/com/github/zagum/speechrecognitionview/ExampleTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..8bc5f2f1b249b963ff4ecaa29d75457bca730027
--- /dev/null
+++ b/speechrecognitionview/src/test/java/com/github/zagum/speechrecognitionview/ExampleTest.java
@@ -0,0 +1,9 @@
+package com.github.zagum.speechrecognitionview;
+
+import org.junit.Test;
+
+public class ExampleTest {
+ @Test
+ public void onStart() {
+ }
+}