├── .github ├── FUNDING.yml └── workflows │ └── android.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── examples └── demoapp │ ├── .gitignore │ ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── net │ │ │ └── gotev │ │ │ └── speechdemo │ │ │ ├── App.java │ │ │ └── MainActivity.java │ │ └── res │ │ ├── drawable-hdpi │ │ └── ic_mic.png │ │ ├── drawable-mdpi │ │ └── ic_mic.png │ │ ├── drawable-xhdpi │ │ └── ic_mic.png │ │ ├── drawable-xxhdpi │ │ └── ic_mic.png │ │ ├── drawable-xxxhdpi │ │ └── ic_mic.png │ │ ├── layout │ │ └── activity_main.xml │ │ ├── menu │ │ └── main_menu.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── manifest.gradle ├── release ├── settings.gradle └── speech ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── proguard-rules.pro └── src ├── androidTest └── java │ └── net │ └── gotev │ └── speech │ └── ApplicationTest.java ├── main ├── AndroidManifest.xml └── java │ └── net │ └── gotev │ └── speech │ ├── DefaultLoggerDelegate.java │ ├── DelayedOperation.java │ ├── GoogleVoiceTypingDisabledException.java │ ├── Logger.java │ ├── Speech.java │ ├── SpeechDelegate.java │ ├── SpeechRecognitionException.java │ ├── SpeechRecognitionNotAvailable.java │ ├── SpeechUtil.java │ ├── SupportedLanguagesListener.java │ ├── TextToSpeechCallback.java │ ├── TtsProgressListener.java │ ├── UnsupportedReason.java │ ├── engine │ ├── BaseSpeechRecognitionEngine.java │ ├── BaseTextToSpeechEngine.java │ ├── DummyOnInitListener.java │ ├── SpeechRecognitionEngine.java │ └── TextToSpeechEngine.java │ └── ui │ ├── SpeechBar.java │ ├── SpeechProgressView.java │ └── animators │ ├── BarParamsAnimator.java │ ├── BarRmsAnimator.java │ ├── IdleAnimator.java │ ├── RmsAnimator.java │ ├── RotatingAnimator.java │ └── TransformAnimator.java └── test └── java └── net └── gotev └── speech └── ExampleUnitTest.java /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://paypal.me/alexgt"] 2 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | android-test: 11 | runs-on: macos-latest 12 | 13 | steps: 14 | - name: checkout 15 | uses: actions/checkout@v2 16 | 17 | - name: run tests 18 | uses: reactivecircus/android-emulator-runner@v2 19 | with: 20 | api-level: 29 21 | script: ./gradlew connectedCheck 22 | 23 | build: 24 | runs-on: ubuntu-latest 25 | 26 | steps: 27 | - uses: actions/checkout@v2 28 | - name: set up JDK 1.8 29 | uses: actions/setup-java@v1 30 | with: 31 | java-version: 1.8 32 | - name: Build with Gradle 33 | run: ./gradlew clean build 34 | 35 | build-demo-app: 36 | runs-on: ubuntu-latest 37 | 38 | steps: 39 | - uses: actions/checkout@v2 40 | - name: set up JDK 1.8 41 | uses: actions/setup-java@v1 42 | with: 43 | java-version: 1.8 44 | - name: Build with Gradle 45 | run: cd examples/demoapp && ./gradlew clean build 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea/workspace.xml 38 | 39 | # Keystore files 40 | *.jks 41 | .idea 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Speech ![Maven Central](https://img.shields.io/maven-central/v/net.gotev/speech) 2 | #### [Latest version Release Notes and Demo App](https://github.com/gotev/android-speech/releases/latest) | [Demo App Sources](https://github.com/gotev/android-speech/tree/master/examples/demoapp/app/src/main/java/net/gotev/speechdemo) 3 | Android speech recognition and text to speech made easy. 4 | 5 | ## Setup 6 | ### Gradle 7 | ```groovy 8 | implementation 'net.gotev:speech:x.y.z' 9 | ``` 10 | Replace `x.y.z` with ![Maven Central](https://img.shields.io/maven-central/v/net.gotev/speech) 11 | 12 | ## Initialization 13 | To start using the library, you have to initialize it in your Activity 14 | ```java 15 | public class YourActivity extends Activity { 16 | 17 | Override 18 | protected void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.your_layout); 21 | 22 | Speech.init(this, getPackageName()); 23 | } 24 | 25 | @Override 26 | protected void onDestroy() { 27 | // prevent memory leaks when activity is destroyed 28 | Speech.getInstance().shutdown(); 29 | } 30 | } 31 | ``` 32 | 33 | ## Example 34 | You can find a fully working demo app which uses this library in the `examples` directory. Just checkout the project and give it a try. 35 | 36 | ## Usage 37 | ### Speech recognition 38 | Inside an activity: 39 | ```java 40 | try { 41 | // you must have android.permission.RECORD_AUDIO granted at this point 42 | Speech.getInstance().startListening(new SpeechDelegate() { 43 | @Override 44 | public void onStartOfSpeech() { 45 | Log.i("speech", "speech recognition is now active"); 46 | } 47 | 48 | @Override 49 | public void onSpeechRmsChanged(float value) { 50 | Log.d("speech", "rms is now: " + value); 51 | } 52 | 53 | @Override 54 | public void onSpeechPartialResults(List results) { 55 | StringBuilder str = new StringBuilder(); 56 | for (String res : results) { 57 | str.append(res).append(" "); 58 | } 59 | 60 | Log.i("speech", "partial result: " + str.toString().trim()); 61 | } 62 | 63 | @Override 64 | public void onSpeechResult(String result) { 65 | Log.i("speech", "result: " + result); 66 | } 67 | }); 68 | } catch (SpeechRecognitionNotAvailable exc) { 69 | Log.e("speech", "Speech recognition is not available on this device!"); 70 | // You can prompt the user if he wants to install Google App to have 71 | // speech recognition, and then you can simply call: 72 | // 73 | // SpeechUtil.redirectUserToGoogleAppOnPlayStore(this); 74 | // 75 | // to redirect the user to the Google App page on Play Store 76 | } catch (GoogleVoiceTypingDisabledException exc) { 77 | Log.e("speech", "Google voice typing must be enabled!"); 78 | } 79 | ``` 80 | 81 | ### Release resources 82 | In your Activity's `onDestroy`, add: 83 | ```java 84 | @Override 85 | protected void onDestroy() { 86 | Speech.getInstance().shutdown(); 87 | } 88 | ``` 89 | To prevent memory leaks. 90 | 91 | ### Display progress animation 92 | Add this to your layout: 93 | ```xml 94 | 99 | 100 | 104 | 105 | 106 | ``` 107 | It's important that the `SpeechProgressView` is always inside a LinearLayout to function properly. You can adjust width and height accordingly to the bar height settings (see below). 108 | 109 | then, when you start speech recognition, pass also the `SpeechProgressView`: 110 | 111 | ```java 112 | Speech.getInstance().startListening(speechProgressView, speechDelegate); 113 | ``` 114 | 115 | #### Set custom bar colors 116 | You can set all the 5 bar colors as you wish. This is just an example: 117 | ```java 118 | int[] colors = { 119 | ContextCompat.getColor(this, android.R.color.black), 120 | ContextCompat.getColor(this, android.R.color.darker_gray), 121 | ContextCompat.getColor(this, android.R.color.black), 122 | ContextCompat.getColor(this, android.R.color.holo_orange_dark), 123 | ContextCompat.getColor(this, android.R.color.holo_red_dark) 124 | }; 125 | speechProgressView.setColors(colors); 126 | ``` 127 | 128 | #### Set custom maximum bar height 129 | ```java 130 | int[] heights = {60, 76, 58, 80, 55}; 131 | speechProgressView.setBarMaxHeightsInDp(heights); 132 | ``` 133 | 134 | ### Text to speech 135 | Inside an activity: 136 | ```java 137 | Speech.getInstance().say("say something"); 138 | ``` 139 | 140 | You can also provide a callback to receive status: 141 | ```java 142 | Speech.getInstance().say("say something", new TextToSpeechCallback() { 143 | @Override 144 | public void onStart() { 145 | Log.i("speech", "speech started"); 146 | } 147 | 148 | @Override 149 | public void onCompleted() { 150 | Log.i("speech", "speech completed"); 151 | } 152 | 153 | @Override 154 | public void onError() { 155 | Log.i("speech", "speech error"); 156 | } 157 | }); 158 | ``` 159 | 160 | ## Configuration 161 | You can configure various parameters by using the setter methods on the speech instance, which you can get like this anywhere in your code: 162 | ```java 163 | Speech.getInstance() 164 | ``` 165 | Refer to JavaDocs for a complete reference. 166 | 167 | ## Logging 168 | By default the library logging is disabled. You can enable debug log by invoking: 169 | ```java 170 | Logger.setLogLevel(LogLevel.DEBUG); 171 | ``` 172 | wherever you want in your code. You can adjust the level of detail from DEBUG to OFF. 173 | 174 | The library logger uses `android.util.Log` by default, so you will get the output in `LogCat`. If you want to redirect logs to different output or use a different logger, you can provide your own delegate implementation like this: 175 | ```java 176 | Logger.setLoggerDelegate(new Logger.LoggerDelegate() { 177 | @Override 178 | public void error(String tag, String message) { 179 | //your own implementation here 180 | } 181 | 182 | @Override 183 | public void error(String tag, String message, Throwable exception) { 184 | //your own implementation here 185 | } 186 | 187 | @Override 188 | public void debug(String tag, String message) { 189 | //your own implementation here 190 | } 191 | 192 | @Override 193 | public void info(String tag, String message) { 194 | //your own implementation here 195 | } 196 | }); 197 | ``` 198 | 199 | ## Get current locale and voice (since 1.5.0) 200 | Use `Speech.getInstance().getSpeechToTextLanguage()` and `Speech.getinstance().getTextToSpeechVoice()`. Check the demo app for a complete example. 201 | 202 | ## Get supported Speech To Text languages and Text To Speech voices (since 1.5.0) 203 | Use `Speech.getInstance().getSupportedSpeechToTextLanguages(listener)` and `Speech.getInstance().getSupportedTextToSpeechVoices()`. Check the demo app for a complete example. 204 | 205 | ## Set Speech To Text Language and Text To Speech voice 206 | Use `Speech.getInstance().setLocale(locale)` and `Speech.getInstance().setVoice(voice)`. Check the demo app for a complete example. 207 | 208 | > When you set the locale, the voice is automatically changed to the default voice of that language. If you want to set a particular voice, remember to re-set it every time you change the locale, too. 209 | 210 | ## Credits 211 | Thanks to @zagum for the original implementation of the [speech recognition view](https://github.com/zagum/SpeechRecognitionView). 212 | 213 | ## License 214 | 215 | Copyright (C) 2019 Aleksandar Gotev 216 | 217 | Licensed under the Apache License, Version 2.0 (the "License"); 218 | you may not use this file except in compliance with the License. 219 | You may obtain a copy of the License at 220 | 221 | http://www.apache.org/licenses/LICENSE-2.0 222 | 223 | Unless required by applicable law or agreed to in writing, software 224 | distributed under the License is distributed on an "AS IS" BASIS, 225 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 226 | See the License for the specific language governing permissions and 227 | limitations under the License. 228 | 229 | ## Contributors 230 | Thanks to [Kristiyan Petrov](https://github.com/kristiyanP) for code review, bug fixes and library improvement ideas. 231 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | apply from: 'manifest.gradle' 5 | 6 | repositories { 7 | google() 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | classpath "com.android.tools.build:gradle:$gradle_version" 13 | 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | google() 22 | mavenCentral() 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /examples/demoapp/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | -------------------------------------------------------------------------------- /examples/demoapp/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /examples/demoapp/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion target_sdk 5 | 6 | defaultConfig { 7 | applicationId demo_app_id 8 | minSdkVersion min_sdk 9 | targetSdkVersion target_sdk 10 | versionCode version_code 11 | versionName library_version 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | 22 | compileOptions { 23 | sourceCompatibility JavaVersion.VERSION_1_8 24 | targetCompatibility JavaVersion.VERSION_1_8 25 | } 26 | } 27 | 28 | 29 | dependencies { 30 | // Testing - https://developer.android.com/training/testing/set-up-project 31 | testImplementation "junit:junit:$junit_version" 32 | testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" 33 | 34 | // Core library 35 | androidTestImplementation "androidx.test:core:$androidx_test_core_version" 36 | 37 | // AndroidJUnitRunner and JUnit Rules 38 | androidTestImplementation "androidx.test:runner:$androidx_test_runner_version" 39 | androidTestImplementation "androidx.test:rules:$androidx_test_rules_version" 40 | 41 | // Assertions 42 | androidTestImplementation "androidx.test.ext:junit:$androidx_test_ext_junit_version" 43 | androidTestImplementation "androidx.test.ext:truth:$androidx_test_ext_truth_version" 44 | androidTestImplementation "com.google.truth:truth:$truth_version" 45 | 46 | // Espresso dependencies 47 | androidTestImplementation "androidx.test.espresso:espresso-core:$androidx_test_espresso_version" 48 | 49 | // Support 50 | implementation "androidx.appcompat:appcompat:$androidx_appcompat_version" 51 | implementation 'com.google.android.material:material:1.0.0' 52 | 53 | implementation project(':speech') 54 | } 55 | -------------------------------------------------------------------------------- /examples/demoapp/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/alex/workspace/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/java/net/gotev/speechdemo/App.java: -------------------------------------------------------------------------------- 1 | package net.gotev.speechdemo; 2 | 3 | import android.app.Application; 4 | 5 | import net.gotev.speech.Logger; 6 | 7 | /** 8 | * @author Aleksandar Gotev 9 | */ 10 | public class App extends Application { 11 | @Override 12 | public void onCreate() { 13 | super.onCreate(); 14 | 15 | Logger.setLogLevel(Logger.LogLevel.DEBUG); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/java/net/gotev/speechdemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package net.gotev.speechdemo; 2 | 3 | import android.Manifest; 4 | import android.content.DialogInterface; 5 | import android.content.pm.PackageManager; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.speech.tts.TextToSpeech; 9 | import android.speech.tts.Voice; 10 | import android.view.Menu; 11 | import android.view.MenuItem; 12 | import android.view.View; 13 | import android.widget.Button; 14 | import android.widget.EditText; 15 | import android.widget.ImageButton; 16 | import android.widget.LinearLayout; 17 | import android.widget.TextView; 18 | import android.widget.Toast; 19 | 20 | import net.gotev.speech.*; 21 | import net.gotev.speech.ui.SpeechProgressView; 22 | import net.gotev.toyproject.R; 23 | 24 | import java.util.*; 25 | 26 | import androidx.annotation.NonNull; 27 | import androidx.appcompat.app.AlertDialog; 28 | import androidx.appcompat.app.AppCompatActivity; 29 | import androidx.core.app.ActivityCompat; 30 | import androidx.core.content.ContextCompat; 31 | 32 | public class MainActivity extends AppCompatActivity implements SpeechDelegate { 33 | 34 | private final int PERMISSIONS_REQUEST = 1; 35 | private static final String LOG_TAG = MainActivity.class.getSimpleName(); 36 | 37 | private ImageButton button; 38 | private Button speak; 39 | private TextView text; 40 | private EditText textToSpeech; 41 | private SpeechProgressView progress; 42 | private LinearLayout linearLayout; 43 | 44 | private TextToSpeech.OnInitListener mTttsInitListener = new TextToSpeech.OnInitListener() { 45 | @Override 46 | public void onInit(final int status) { 47 | switch (status) { 48 | case TextToSpeech.SUCCESS: 49 | Logger.info(LOG_TAG, "TextToSpeech engine successfully started"); 50 | break; 51 | 52 | case TextToSpeech.ERROR: 53 | Logger.error(LOG_TAG, "Error while initializing TextToSpeech engine!"); 54 | break; 55 | 56 | default: 57 | Logger.error(LOG_TAG, "Unknown TextToSpeech status: " + status); 58 | break; 59 | } 60 | } 61 | }; 62 | 63 | @Override 64 | protected void onCreate(Bundle savedInstanceState) { 65 | super.onCreate(savedInstanceState); 66 | setContentView(R.layout.activity_main); 67 | 68 | Speech.init(this, getPackageName(), mTttsInitListener); 69 | 70 | linearLayout = findViewById(R.id.linearLayout); 71 | 72 | button = findViewById(R.id.button); 73 | button.setOnClickListener(view -> onButtonClick()); 74 | 75 | speak = findViewById(R.id.speak); 76 | speak.setOnClickListener(view -> onSpeakClick()); 77 | 78 | text = findViewById(R.id.text); 79 | textToSpeech = findViewById(R.id.textToSpeech); 80 | progress = findViewById(R.id.progress); 81 | 82 | int[] colors = { 83 | ContextCompat.getColor(this, android.R.color.black), 84 | ContextCompat.getColor(this, android.R.color.darker_gray), 85 | ContextCompat.getColor(this, android.R.color.black), 86 | ContextCompat.getColor(this, android.R.color.holo_orange_dark), 87 | ContextCompat.getColor(this, android.R.color.holo_red_dark) 88 | }; 89 | progress.setColors(colors); 90 | } 91 | 92 | @Override 93 | public boolean onCreateOptionsMenu(Menu menu) { 94 | getMenuInflater().inflate(R.menu.main_menu, menu); 95 | return true; 96 | } 97 | 98 | @Override 99 | public boolean onOptionsItemSelected(MenuItem item) { 100 | switch (item.getItemId()) { 101 | case R.id.supportedSTTLanguages: 102 | onSetSpeechToTextLanguage(); 103 | return true; 104 | 105 | case R.id.supportedTTSLanguages: 106 | onSetTextToSpeechVoice(); 107 | return true; 108 | 109 | default: 110 | return super.onOptionsItemSelected(item); 111 | } 112 | } 113 | 114 | private void onSetSpeechToTextLanguage() { 115 | Speech.getInstance().getSupportedSpeechToTextLanguages(new SupportedLanguagesListener() { 116 | @Override 117 | public void onSupportedLanguages(List supportedLanguages) { 118 | CharSequence[] items = new CharSequence[supportedLanguages.size()]; 119 | supportedLanguages.toArray(items); 120 | 121 | new AlertDialog.Builder(MainActivity.this) 122 | .setTitle("Current language: " + Speech.getInstance().getSpeechToTextLanguage()) 123 | .setItems(items, new DialogInterface.OnClickListener() { 124 | @Override 125 | public void onClick(DialogInterface dialogInterface, int i) { 126 | Locale locale; 127 | 128 | if (Build.VERSION.SDK_INT >= 21) { 129 | locale = Locale.forLanguageTag(supportedLanguages.get(i)); 130 | } else { 131 | String[] langParts = supportedLanguages.get(i).split("-"); 132 | 133 | if (langParts.length >= 2) { 134 | locale = new Locale(langParts[0], langParts[1]); 135 | } else { 136 | locale = new Locale(langParts[0]); 137 | } 138 | } 139 | 140 | Speech.getInstance().setLocale(locale); 141 | Toast.makeText(MainActivity.this, "Selected: " + items[i], Toast.LENGTH_LONG).show(); 142 | } 143 | }) 144 | .setPositiveButton("Cancel", null) 145 | .create() 146 | .show(); 147 | } 148 | 149 | @Override 150 | public void onNotSupported(UnsupportedReason reason) { 151 | switch (reason) { 152 | case GOOGLE_APP_NOT_FOUND: 153 | showSpeechNotSupportedDialog(); 154 | break; 155 | 156 | case EMPTY_SUPPORTED_LANGUAGES: 157 | new AlertDialog.Builder(MainActivity.this) 158 | .setTitle(R.string.set_stt_langs) 159 | .setMessage(R.string.no_langs) 160 | .setPositiveButton("OK", null) 161 | .show(); 162 | break; 163 | } 164 | } 165 | }); 166 | } 167 | 168 | private void onSetTextToSpeechVoice() { 169 | List supportedVoices = Speech.getInstance().getSupportedTextToSpeechVoices(); 170 | 171 | if (supportedVoices.isEmpty()) { 172 | new AlertDialog.Builder(this) 173 | .setTitle(R.string.set_tts_voices) 174 | .setMessage(R.string.no_tts_voices) 175 | .setPositiveButton("OK", null) 176 | .show(); 177 | return; 178 | } 179 | 180 | // Sort TTS voices 181 | Collections.sort(supportedVoices, (v1, v2) -> v1.toString().compareTo(v2.toString())); 182 | 183 | CharSequence[] items = new CharSequence[supportedVoices.size()]; 184 | Iterator iterator = supportedVoices.iterator(); 185 | int i = 0; 186 | 187 | while (iterator.hasNext()) { 188 | Voice voice = iterator.next(); 189 | 190 | items[i] = voice.toString(); 191 | i++; 192 | } 193 | 194 | new AlertDialog.Builder(MainActivity.this) 195 | .setTitle("Current: " + Speech.getInstance().getTextToSpeechVoice()) 196 | .setItems(items, new DialogInterface.OnClickListener() { 197 | @Override 198 | public void onClick(DialogInterface dialogInterface, int i) { 199 | Speech.getInstance().setVoice(supportedVoices.get(i)); 200 | Toast.makeText(MainActivity.this, "Selected: " + items[i], Toast.LENGTH_LONG).show(); 201 | } 202 | }) 203 | .setPositiveButton("Cancel", null) 204 | .create() 205 | .show(); 206 | } 207 | 208 | @Override 209 | protected void onDestroy() { 210 | super.onDestroy(); 211 | Speech.getInstance().shutdown(); 212 | } 213 | 214 | private void onButtonClick() { 215 | if (Speech.getInstance().isListening()) { 216 | Speech.getInstance().stopListening(); 217 | } else { 218 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { 219 | onRecordAudioPermissionGranted(); 220 | } else { 221 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST); 222 | } 223 | } 224 | } 225 | 226 | @Override 227 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 228 | if (requestCode != PERMISSIONS_REQUEST) { 229 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 230 | } else { 231 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 232 | // permission was granted, yay! 233 | onRecordAudioPermissionGranted(); 234 | } else { 235 | // permission denied, boo! 236 | Toast.makeText(MainActivity.this, R.string.permission_required, Toast.LENGTH_LONG).show(); 237 | } 238 | } 239 | } 240 | 241 | private void onRecordAudioPermissionGranted() { 242 | button.setVisibility(View.GONE); 243 | linearLayout.setVisibility(View.VISIBLE); 244 | 245 | try { 246 | Speech.getInstance().stopTextToSpeech(); 247 | Speech.getInstance().startListening(progress, MainActivity.this); 248 | 249 | } catch (SpeechRecognitionNotAvailable exc) { 250 | showSpeechNotSupportedDialog(); 251 | 252 | } catch (GoogleVoiceTypingDisabledException exc) { 253 | showEnableGoogleVoiceTyping(); 254 | } 255 | } 256 | 257 | private void onSpeakClick() { 258 | if (textToSpeech.getText().toString().trim().isEmpty()) { 259 | Toast.makeText(this, R.string.input_something, Toast.LENGTH_LONG).show(); 260 | return; 261 | } 262 | 263 | Speech.getInstance().say(textToSpeech.getText().toString().trim(), new TextToSpeechCallback() { 264 | @Override 265 | public void onStart() { 266 | Toast.makeText(MainActivity.this, "TTS onStart", Toast.LENGTH_SHORT).show(); 267 | } 268 | 269 | @Override 270 | public void onCompleted() { 271 | Toast.makeText(MainActivity.this, "TTS onCompleted", Toast.LENGTH_SHORT).show(); 272 | } 273 | 274 | @Override 275 | public void onError() { 276 | Toast.makeText(MainActivity.this, "TTS onError", Toast.LENGTH_SHORT).show(); 277 | } 278 | }); 279 | } 280 | 281 | @Override 282 | public void onStartOfSpeech() { 283 | } 284 | 285 | @Override 286 | public void onSpeechRmsChanged(float value) { 287 | //Log.d(getClass().getSimpleName(), "Speech recognition rms is now " + value + "dB"); 288 | } 289 | 290 | @Override 291 | public void onSpeechResult(String result) { 292 | 293 | button.setVisibility(View.VISIBLE); 294 | linearLayout.setVisibility(View.GONE); 295 | 296 | text.setText(result); 297 | 298 | if (result.isEmpty()) { 299 | Speech.getInstance().say(getString(R.string.repeat)); 300 | 301 | } else { 302 | Speech.getInstance().say(result); 303 | } 304 | } 305 | 306 | @Override 307 | public void onSpeechPartialResults(List results) { 308 | text.setText(""); 309 | for (String partial : results) { 310 | text.append(partial + " "); 311 | } 312 | } 313 | 314 | private void showSpeechNotSupportedDialog() { 315 | DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { 316 | @Override 317 | public void onClick(DialogInterface dialog, int which) { 318 | switch (which) { 319 | case DialogInterface.BUTTON_POSITIVE: 320 | SpeechUtil.redirectUserToGoogleAppOnPlayStore(MainActivity.this); 321 | break; 322 | 323 | case DialogInterface.BUTTON_NEGATIVE: 324 | break; 325 | } 326 | } 327 | }; 328 | 329 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 330 | builder.setMessage(R.string.speech_not_available) 331 | .setCancelable(false) 332 | .setPositiveButton(R.string.yes, dialogClickListener) 333 | .setNegativeButton(R.string.no, dialogClickListener) 334 | .show(); 335 | } 336 | 337 | private void showEnableGoogleVoiceTyping() { 338 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 339 | builder.setMessage(R.string.enable_google_voice_typing) 340 | .setCancelable(false) 341 | .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { 342 | @Override 343 | public void onClick(DialogInterface dialogInterface, int i) { 344 | // do nothing 345 | } 346 | }) 347 | .show(); 348 | } 349 | 350 | } 351 | -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/drawable-hdpi/ic_mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-speech/1352d77ecdb757164f83e51797827fb445d5be25/examples/demoapp/app/src/main/res/drawable-hdpi/ic_mic.png -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/drawable-mdpi/ic_mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-speech/1352d77ecdb757164f83e51797827fb445d5be25/examples/demoapp/app/src/main/res/drawable-mdpi/ic_mic.png -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/drawable-xhdpi/ic_mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-speech/1352d77ecdb757164f83e51797827fb445d5be25/examples/demoapp/app/src/main/res/drawable-xhdpi/ic_mic.png -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/drawable-xxhdpi/ic_mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-speech/1352d77ecdb757164f83e51797827fb445d5be25/examples/demoapp/app/src/main/res/drawable-xxhdpi/ic_mic.png -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/drawable-xxxhdpi/ic_mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gotev/android-speech/1352d77ecdb757164f83e51797827fb445d5be25/examples/demoapp/app/src/main/res/drawable-xxxhdpi/ic_mic.png -------------------------------------------------------------------------------- /examples/demoapp/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 19 | 20 | 28 | 29 | 33 | 34 | 35 | 36 | 44 | 45 |