├── .github └── workflows │ └── android.yml ├── .gitignore ├── .idea ├── .gitignore ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── compiler.xml ├── deploymentTargetSelector.xml ├── dictionaries │ └── tomyang.xml ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── kotlinc.xml ├── migrations.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── .kotlin └── errors │ └── errors-1734592217997.log ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle.kts ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── istomyang │ │ └── edgetss │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── ic_launcher-playstore.png │ ├── java │ │ └── com │ │ │ └── istomyang │ │ │ └── edgetss │ │ │ ├── data │ │ │ ├── LogRepository.kt │ │ │ └── SpeakerRepository.kt │ │ │ ├── service │ │ │ └── EdgeTTSService.kt │ │ │ ├── ui │ │ │ ├── MainActivity.kt │ │ │ ├── main │ │ │ │ ├── LogView.kt │ │ │ │ ├── LogViewModel.kt │ │ │ │ ├── MainView.kt │ │ │ │ ├── SpeakerView.kt │ │ │ │ ├── SpeakerViewModel.kt │ │ │ │ └── component │ │ │ │ │ ├── Button.kt │ │ │ │ │ └── Picker.kt │ │ │ └── theme │ │ │ │ ├── Color.kt │ │ │ │ ├── Theme.kt │ │ │ │ └── Type.kt │ │ │ └── utils │ │ │ ├── Codec.kt │ │ │ ├── CodecTest.kt │ │ │ └── Player.kt │ └── res │ │ ├── drawable │ │ ├── ic_launcher_foreground.xml │ │ └── icon_launch.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── values │ │ ├── colors.xml │ │ ├── ic_launcher_background.xml │ │ ├── strings.xml │ │ └── themes.xml │ │ └── xml │ │ ├── backup_rules.xml │ │ └── data_extraction_rules.xml │ └── test │ └── java │ └── com │ └── istomyang │ └── edgetss │ ├── BufferUnitTest.kt │ ├── ExampleUnitTest.kt │ └── FlowUnitTest.kt ├── build.gradle.kts ├── docs └── images │ ├── Screenshot_2024-12-25-14-59-03-429_com.istomyang.edgetss.release.jpg │ └── Screenshot_2024-12-25-14-59-36-340_com.istomyang.edgetss.release.jpg ├── engine ├── .gitignore ├── build.gradle.kts └── src │ ├── main │ └── java │ │ └── com │ │ └── istomyang │ │ └── tts_engine │ │ ├── DRM.kt │ │ ├── SpeakerManager.kt │ │ └── TTS.kt │ └── test │ └── java │ └── com │ └── istomyang │ └── tts_engine │ ├── ChannelUnitTest.kt │ ├── ExampleUnitTest.kt │ └── SomeUnitTest.kt ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle.kts /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android Build and Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-java@v4 17 | with: 18 | distribution: 'temurin' 19 | java-version: '17' 20 | - uses: gradle/actions/setup-gradle@v3 21 | 22 | - name: Cache Gradle dependencies 23 | uses: actions/cache@v3 24 | with: 25 | path: ~/.gradle/caches 26 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*') }} 27 | restore-keys: | 28 | ${{ runner.os }}-gradle- 29 | 30 | - name: Build APK 31 | run: | 32 | ./gradlew assembleRelease \ 33 | -Psigning.keyAlias=${{ secrets.ALIAS }} \ 34 | -Psigning.keyPassword=${{ secrets.KEY_PASSWORD }} \ 35 | -Psigning.storeFile=$HOME/keystore.jks \ 36 | -Psigning.storePassword=${{ secrets.KEYSTORE_PASSWORD }} 37 | 38 | - name: Upload APKs to GitHub Release 39 | uses: ncipollo/release-action@v1 40 | with: 41 | allowUpdates: true 42 | artifacts: app/build/outputs/apk/release/app-release.apk 43 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 12 | 13 | 125 | 126 | 129 | 130 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/deploymentTargetSelector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/dictionaries/tomyang.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 57 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/migrations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.kotlin/errors/errors-1734592217997.log: -------------------------------------------------------------------------------- 1 | kotlin version: 2.0.21 2 | error message: The daemon has terminated unexpectedly on startup attempt #1 with error code: 0. The daemon process output: 3 | 1. Kotlin compile daemon is ready 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Edge-TTS for Android 2 | 3 | Edge-TTS for Android is a text-to-speech service that uses the Edge-TTS API to convert text to 4 | speech. 5 | 6 | ## Screenshots 7 | 8 |
9 | Screenshot 1 10 | Screenshot 2 11 |
-------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /debug 3 | /release -------------------------------------------------------------------------------- /app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.android.application) 3 | alias(libs.plugins.kotlin.android) 4 | alias(libs.plugins.compose.compiler) 5 | id("com.google.devtools.ksp") 6 | } 7 | 8 | android { 9 | namespace = "com.istomyang.edgetss" 10 | compileSdk = 34 11 | 12 | defaultConfig { 13 | applicationId = "com.istomyang.edgetss" 14 | minSdk = 29 15 | targetSdk = 34 16 | versionCode = 1 17 | versionName = "1.5.3" 18 | 19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 20 | vectorDrawables { 21 | useSupportLibrary = true 22 | } 23 | } 24 | 25 | buildTypes { 26 | release { 27 | resValue("string", "app_name", "Edge TSS") 28 | applicationIdSuffix = ".release" 29 | isShrinkResources = true 30 | isMinifyEnabled = true 31 | proguardFiles( 32 | getDefaultProguardFile("proguard-android-optimize.txt"), 33 | "proguard-rules.pro" 34 | ) 35 | signingConfig = signingConfigs.getByName("debug") 36 | } 37 | create("prerelease") { 38 | initWith(getByName("release")) 39 | resValue("string", "app_name", "Edge TSS β") 40 | applicationIdSuffix = ".prerelease" 41 | } 42 | debug { 43 | resValue("string", "app_name", "Edge TSS α") 44 | applicationIdSuffix = ".debug" 45 | } 46 | } 47 | compileOptions { 48 | sourceCompatibility = JavaVersion.VERSION_17 49 | targetCompatibility = JavaVersion.VERSION_17 50 | } 51 | kotlinOptions { 52 | jvmTarget = "17" 53 | } 54 | buildFeatures { 55 | compose = true 56 | } 57 | composeOptions { 58 | kotlinCompilerExtensionVersion = "1.5.1" 59 | } 60 | packaging { 61 | resources { 62 | excludes += "/META-INF/{AL2.0,LGPL2.1}" 63 | } 64 | } 65 | } 66 | 67 | composeCompiler { 68 | reportsDestination = layout.buildDirectory.dir("compose_compiler") 69 | // stabilityConfigurationFile = rootProject.layout.projectDirectory.file("stability_config.conf") 70 | } 71 | 72 | dependencies { 73 | implementation(project(":engine")) 74 | 75 | implementation(libs.junit.junit) 76 | val ktorVersion = "3.0.2" 77 | implementation("io.ktor:ktor-client-core:$ktorVersion") 78 | implementation("io.ktor:ktor-client-cio:$ktorVersion") 79 | implementation("io.ktor:ktor-client-websockets:$ktorVersion") 80 | 81 | implementation(libs.androidx.room.room.runtime2) 82 | implementation(libs.androidx.room.ktx) 83 | implementation(libs.androidx.datastore.core.android) 84 | implementation(libs.androidx.constraintlayout) 85 | implementation(libs.androidx.lifecycle.runtime.compose.android) 86 | testImplementation(libs.androidx.room.testing) 87 | ksp(libs.androidx.room.compiler) 88 | 89 | implementation(libs.androidx.datastore.preferences) 90 | 91 | implementation(libs.androidx.core.ktx) 92 | implementation(libs.androidx.lifecycle.runtime.ktx) 93 | implementation(libs.androidx.activity.compose) 94 | implementation(platform(libs.androidx.compose.bom)) 95 | implementation(libs.androidx.ui) 96 | implementation(libs.androidx.ui.graphics) 97 | implementation(libs.androidx.ui.tooling.preview) 98 | implementation(libs.androidx.material3) 99 | testImplementation(libs.junit) 100 | androidTestImplementation(libs.androidx.junit) 101 | androidTestImplementation(libs.androidx.espresso.core) 102 | androidTestImplementation(platform(libs.androidx.compose.bom)) 103 | androidTestImplementation(libs.androidx.ui.test.junit4) 104 | debugImplementation(libs.androidx.ui.tooling) 105 | debugImplementation(libs.androidx.ui.test.manifest) 106 | 107 | implementation(libs.androidx.lifecycle.viewmodel.compose) 108 | implementation(libs.material.icons.extended) 109 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/istomyang/edgetss/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.istomyang.edgetss", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 17 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /app/src/main/ic_launcher-playstore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yyangv/edge-tts-android/75eccb225c70ac66c38aa8370e7a489fa69b1374/app/src/main/ic_launcher-playstore.png -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/data/LogRepository.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.data 2 | 3 | import android.content.Context 4 | import androidx.annotation.GuardedBy 5 | import androidx.datastore.core.DataStore 6 | import androidx.datastore.preferences.core.Preferences 7 | import androidx.datastore.preferences.core.booleanPreferencesKey 8 | import androidx.datastore.preferences.core.edit 9 | import androidx.datastore.preferences.preferencesDataStore 10 | import androidx.room.ColumnInfo 11 | import androidx.room.Dao 12 | import androidx.room.Database 13 | import androidx.room.Entity 14 | import androidx.room.Insert 15 | import androidx.room.PrimaryKey 16 | import androidx.room.Query 17 | import androidx.room.Room 18 | import androidx.room.RoomDatabase 19 | import kotlinx.coroutines.CoroutineScope 20 | import kotlinx.coroutines.Dispatchers 21 | import kotlinx.coroutines.flow.first 22 | import kotlinx.coroutines.flow.map 23 | import kotlinx.coroutines.launch 24 | import java.time.LocalDateTime 25 | import java.time.ZoneOffset 26 | import kotlin.reflect.KProperty 27 | 28 | val Context.repositoryLog by LogRepositoryDelegate() 29 | 30 | class LogRepository( 31 | private val localDataSource: LogLocalDataSource, 32 | private val preferenceDataSource: DataStore 33 | ) { 34 | val enabled = preferenceDataSource.data.map { it[KEY_ENABLED] == true } 35 | val enabledDebug = preferenceDataSource.data.map { it[KEY_ENABLED_DEBUG] == true } 36 | 37 | suspend fun open(enabled: Boolean = true) { 38 | preferenceDataSource.edit { 39 | it[KEY_ENABLED] = enabled 40 | } 41 | } 42 | 43 | suspend fun openDebug(enabled: Boolean = true) { 44 | preferenceDataSource.edit { 45 | it[KEY_ENABLED_DEBUG] = enabled 46 | } 47 | } 48 | 49 | private fun insert(domain: String, level: LogLevel, message: String) { 50 | CoroutineScope(Dispatchers.IO).launch { 51 | if (!enabled.first()) { 52 | return@launch 53 | } 54 | val log = Log( 55 | domain = domain, 56 | level = level.name, 57 | message = message, 58 | createdAt = timestampBefore(0, 0, 0) 59 | ) 60 | localDataSource.dao.inert(log) 61 | } 62 | } 63 | 64 | fun info(domain: String, message: String) = insert(domain = domain, level = LogLevel.INFO, message = message) 65 | 66 | suspend fun debug(domain: String, message: String) { 67 | if (!enabledDebug.first()) { 68 | return 69 | } 70 | insert(domain = domain, level = LogLevel.DEBUG, message = message) 71 | } 72 | 73 | fun error(domain: String, message: String) = insert(domain = domain, level = LogLevel.ERROR, message = message) 74 | 75 | suspend fun query(levels: List, o: Int, l: Int) = localDataSource.dao.query(levels, o, l) 76 | 77 | suspend fun queryAll(levels: List) = localDataSource.dao.queryAll(levels) 78 | 79 | suspend fun clear() { 80 | localDataSource.dao.clear() 81 | } 82 | 83 | suspend fun clearDebugBefore1Hour() { 84 | val before = timestampBefore(0, 1, 0) 85 | localDataSource.dao.clearDebug(before) 86 | } 87 | 88 | companion object { 89 | fun create(context: Context): LogRepository { 90 | val db = Room.databaseBuilder( 91 | context, 92 | LogDatabase::class.java, 93 | "log" 94 | ).build() 95 | val localDS = LogLocalDataSource(db.logDao()) 96 | val preferenceDS = context.dateStoreLog 97 | return LogRepository(localDS, preferenceDS) 98 | } 99 | 100 | fun timestampBefore(min: Long, hour: Long, day: Long): Long { 101 | val now = LocalDateTime.now() 102 | val targetDateTime = now.minusMinutes(min).minusHours(hour).minusDays(day) 103 | return targetDateTime.toInstant(ZoneOffset.UTC).toEpochMilli() 104 | } 105 | 106 | private val KEY_ENABLED = booleanPreferencesKey("enabled") 107 | private val KEY_ENABLED_DEBUG = booleanPreferencesKey("enabled-debug") 108 | } 109 | } 110 | 111 | private val Context.dateStoreLog by preferencesDataStore("log") 112 | 113 | class LogRepositoryDelegate { 114 | private val lock = Any() 115 | 116 | @GuardedBy("lock") 117 | @Volatile 118 | private var instance: LogRepository? = null 119 | 120 | operator fun getValue(thisRef: Context, property: KProperty<*>): LogRepository { 121 | return instance ?: synchronized(lock) { 122 | if (instance == null) { 123 | val applicationContext = thisRef.applicationContext 124 | instance = LogRepository.create(applicationContext) 125 | } 126 | instance!! 127 | } 128 | } 129 | } 130 | 131 | enum class LogLevel { 132 | DEBUG, 133 | INFO, 134 | ERROR 135 | } 136 | 137 | // region LogDataSource 138 | 139 | class LogLocalDataSource(val dao: LogDao) 140 | 141 | @Database(entities = [Log::class], version = 1, exportSchema = false) 142 | abstract class LogDatabase : RoomDatabase() { 143 | abstract fun logDao(): LogDao 144 | } 145 | 146 | @Dao 147 | interface LogDao { 148 | @Insert 149 | suspend fun insertBatch(logs: List) 150 | 151 | @Insert 152 | suspend fun inert(log: Log) 153 | 154 | @Query("SELECT * FROM log WHERE level IN (:levels) ORDER BY created_at ASC LIMIT :l OFFSET :o") 155 | suspend fun query( 156 | levels: List, 157 | o: Int = 0, 158 | l: Int = 100 159 | ): List 160 | 161 | @Query("SELECT * FROM log WHERE level IN (:levels) ORDER BY created_at ASC") 162 | suspend fun queryAll( 163 | levels: List, 164 | ): List 165 | 166 | @Query("DELETE FROM log") 167 | suspend fun clear() 168 | 169 | @Query("DELETE FROM log WHERE level = 'DEBUG' AND created_at < :before") 170 | suspend fun clearDebug(before: Long) 171 | } 172 | 173 | @Entity(tableName = "log", indices = []) 174 | data class Log( 175 | @PrimaryKey(autoGenerate = true) val id: Int = 0, 176 | @ColumnInfo(name = "domain") val domain: String, 177 | @ColumnInfo(name = "level") val level: String, 178 | @ColumnInfo(name = "message") val message: String, 179 | @ColumnInfo(name = "created_at") val createdAt: Long // in ms 180 | ) 181 | 182 | // endregion -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/data/SpeakerRepository.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.data 2 | 3 | import android.content.Context 4 | import androidx.annotation.GuardedBy 5 | import androidx.datastore.core.DataStore 6 | import androidx.datastore.preferences.core.Preferences 7 | import androidx.datastore.preferences.core.booleanPreferencesKey 8 | import androidx.datastore.preferences.core.edit 9 | import androidx.datastore.preferences.core.stringPreferencesKey 10 | import androidx.datastore.preferences.preferencesDataStore 11 | import androidx.room.ColumnInfo 12 | import androidx.room.Dao 13 | import androidx.room.Database 14 | import androidx.room.Entity 15 | import androidx.room.Index 16 | import androidx.room.Insert 17 | import androidx.room.OnConflictStrategy 18 | import androidx.room.PrimaryKey 19 | import androidx.room.Query 20 | import androidx.room.Room 21 | import androidx.room.RoomDatabase 22 | import com.istomyang.tts_engine.SpeakerManager 23 | import kotlinx.coroutines.CoroutineScope 24 | import kotlinx.coroutines.Dispatchers 25 | import kotlinx.coroutines.flow.Flow 26 | import kotlinx.coroutines.flow.map 27 | import kotlinx.coroutines.launch 28 | import kotlin.reflect.KProperty 29 | 30 | val Context.repositorySpeaker by SpeakerRepositoryDelegate() 31 | 32 | class SpeakerRepository( 33 | private val localDS: SpeakerLocalDataSource, 34 | private val remoteDS: SpeakerRemoteDataSource, 35 | private val preferenceDataSource: DataStore 36 | ) { 37 | private lateinit var voices: List 38 | 39 | suspend fun fetchAll(): Result> { 40 | if (::voices.isInitialized) { 41 | return Result.success(voices) 42 | } 43 | val result = remoteDS.getAll() 44 | if (result.isSuccess) { 45 | voices = result.getOrNull()!! 46 | return Result.success(voices) 47 | } 48 | return Result.failure(result.exceptionOrNull()!!) 49 | } 50 | 51 | suspend fun get(id: String): Voice? { 52 | return localDS.dao.get(id) 53 | } 54 | 55 | fun getActiveFlow(): Flow { 56 | return localDS.dao.getActiveFlow() 57 | } 58 | 59 | suspend fun removeActive() { 60 | localDS.dao.removeActive() 61 | } 62 | 63 | suspend fun setActive(id: String) { 64 | localDS.dao.setActive(id) 65 | } 66 | 67 | suspend fun getActive(): Voice? { 68 | return localDS.dao.getActive() 69 | } 70 | 71 | fun getFlow(): Flow> { 72 | return localDS.dao.getFlow() 73 | } 74 | 75 | suspend fun insert(ids: Set) { 76 | if (!::voices.isInitialized) { 77 | return 78 | } 79 | val save = voices.filter { it.uid in ids } 80 | localDS.dao.inserts(save) 81 | } 82 | 83 | suspend fun delete(ids: Set) { 84 | localDS.dao.delete(ids) 85 | } 86 | 87 | fun audioFormat() = preferenceDataSource.data.map { 88 | it[KEY_AUDIO_FORMAT] ?: SpeakerManager.OutputFormat.Audio24Khz48KbitrateMonoMp3.value 89 | } 90 | 91 | suspend fun setAudioFormat(format: String) { 92 | preferenceDataSource.edit { 93 | it[KEY_AUDIO_FORMAT] = format 94 | } 95 | } 96 | 97 | companion object { 98 | fun create(context: Context): SpeakerRepository { 99 | val db = Room.databaseBuilder( 100 | context, 101 | VoiceDatabase::class.java, 102 | "voice" 103 | ).build() 104 | val localDS = SpeakerLocalDataSource(db.voiceDao()) 105 | val remoteDS = SpeakerRemoteDataSource() 106 | val preferenceDS = context.dateStoreSpeakers 107 | cleanPreviousVersion(preferenceDS) 108 | return SpeakerRepository(localDS, remoteDS, preferenceDS) 109 | } 110 | 111 | private fun cleanPreviousVersion(ds: DataStore) { 112 | CoroutineScope(Dispatchers.IO).launch { 113 | val k1 = booleanPreferencesKey("use-flow") 114 | ds.edit { 115 | it.remove(k1) 116 | } 117 | } 118 | } 119 | 120 | private val KEY_AUDIO_FORMAT = stringPreferencesKey("audio-format") 121 | } 122 | } 123 | 124 | class SpeakerRepositoryDelegate { 125 | private val lock = Any() 126 | 127 | @GuardedBy("lock") 128 | @Volatile 129 | private var instance: SpeakerRepository? = null 130 | 131 | operator fun getValue(thisRef: Context, property: KProperty<*>): SpeakerRepository { 132 | return instance ?: synchronized(lock) { 133 | if (instance == null) { 134 | val applicationContext = thisRef.applicationContext 135 | instance = SpeakerRepository.create(applicationContext) 136 | } 137 | instance!! 138 | } 139 | } 140 | } 141 | 142 | // region SpeakerRemoteDataSource 143 | 144 | class SpeakerRemoteDataSource { 145 | suspend fun getAll(): Result> { 146 | SpeakerManager().list().onSuccess { items -> 147 | val ret = items.map { it -> 148 | Voice( 149 | uid = it.name, 150 | name = it.name, 151 | shortName = it.shortName, 152 | gender = it.gender, 153 | locale = it.locale, 154 | suggestedCodec = it.suggestedCodec, 155 | friendlyName = it.friendlyName, 156 | status = it.status, 157 | contentCategories = it.voiceTag.contentCategories.joinToString(", "), 158 | voicePersonalities = it.voiceTag.voicePersonalities.joinToString(", "), 159 | active = false 160 | ) 161 | } 162 | return Result.success(ret) 163 | }.onFailure { 164 | return Result.failure(it) 165 | } 166 | 167 | return Result.failure(Throwable("error")) 168 | } 169 | } 170 | 171 | // endregion 172 | 173 | // region SpeakerLocalDataSource 174 | 175 | class SpeakerLocalDataSource(val dao: VoiceDao) 176 | 177 | @Database(entities = [Voice::class], version = 1, exportSchema = false) 178 | abstract class VoiceDatabase : RoomDatabase() { 179 | abstract fun voiceDao(): VoiceDao 180 | } 181 | 182 | @Dao 183 | interface VoiceDao { 184 | @Insert(onConflict = OnConflictStrategy.REPLACE) 185 | suspend fun inserts(voice: List) 186 | 187 | @Query("SELECT * FROM voice WHERE uid = :id") 188 | suspend fun get(id: String): Voice? 189 | 190 | @Query("SELECT * FROM voice WHERE uid IN (:ids)") 191 | suspend fun getByIds(ids: Set): List 192 | 193 | @Query("SELECT * FROM voice") 194 | suspend fun getAll(): List 195 | 196 | @Query("DELETE FROM voice WHERE uid IN (:ids)") 197 | suspend fun delete(ids: Set) 198 | 199 | @Query("SELECT * FROM voice") 200 | fun getFlow(): Flow> 201 | 202 | @Query("SELECT * FROM voice WHERE active = 1") 203 | fun getActiveFlow(): Flow 204 | 205 | @Query("SELECT * FROM voice WHERE active = 1") 206 | suspend fun getActive(): Voice? 207 | 208 | @Query("UPDATE voice SET active = 1 WHERE uid = :id") 209 | suspend fun setActive(id: String) 210 | 211 | @Query("UPDATE voice SET active = 0 WHERE active = 1") 212 | suspend fun removeActive() 213 | } 214 | 215 | @Entity(tableName = "voice", indices = [Index("locale")]) 216 | data class Voice( 217 | @PrimaryKey val uid: String, 218 | @ColumnInfo(name = "active") val active: Boolean, 219 | @ColumnInfo(name = "name") val name: String, 220 | @ColumnInfo(name = "short_name") val shortName: String, 221 | @ColumnInfo(name = "gender") val gender: String, 222 | @ColumnInfo(name = "locale") val locale: String, 223 | @ColumnInfo(name = "suggested_codec") val suggestedCodec: String, 224 | @ColumnInfo(name = "friendly_name") val friendlyName: String, 225 | @ColumnInfo(name = "status") val status: String, 226 | @ColumnInfo(name = "content_categories") val contentCategories: String, // split by , 227 | @ColumnInfo(name = "voice_personalities") val voicePersonalities: String, 228 | ) 229 | 230 | // endregion 231 | 232 | 233 | private val Context.dateStoreSpeakers by preferencesDataStore("speakers") 234 | 235 | -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/service/EdgeTTSService.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.service 2 | 3 | import android.media.AudioFormat 4 | import android.speech.tts.SynthesisCallback 5 | import android.speech.tts.SynthesisRequest 6 | import android.speech.tts.TextToSpeech 7 | import android.speech.tts.TextToSpeechService 8 | import android.util.Log 9 | import com.istomyang.edgetss.data.LogRepository 10 | import com.istomyang.edgetss.data.SpeakerRepository 11 | import com.istomyang.edgetss.data.repositoryLog 12 | import com.istomyang.edgetss.data.repositorySpeaker 13 | import com.istomyang.edgetss.utils.Player 14 | import com.istomyang.tts_engine.TTS 15 | import kotlinx.coroutines.CancellationException 16 | import kotlinx.coroutines.CoroutineScope 17 | import kotlinx.coroutines.Dispatchers 18 | import kotlinx.coroutines.cancel 19 | import kotlinx.coroutines.channels.Channel 20 | import kotlinx.coroutines.flow.Flow 21 | import kotlinx.coroutines.flow.transform 22 | import kotlinx.coroutines.launch 23 | import kotlinx.coroutines.runBlocking 24 | 25 | class EdgeTTSService : TextToSpeechService() { 26 | companion object { 27 | private const val LOG_NAME = "EdgeTTSService" 28 | } 29 | 30 | private val scope = CoroutineScope(Dispatchers.IO) 31 | 32 | private lateinit var engine: TTS 33 | private lateinit var player: Player 34 | private lateinit var logRepository: LogRepository 35 | private lateinit var speakerRepository: SpeakerRepository 36 | 37 | private var prepared = false 38 | private var locale: String? = null 39 | private var voiceName: String? = null 40 | private var outputFormat: String? = null 41 | private var sampleRate = 24000 42 | 43 | override fun onCreate() { 44 | super.onCreate() 45 | 46 | val context = this.applicationContext 47 | logRepository = context.repositoryLog 48 | speakerRepository = context.repositorySpeaker 49 | 50 | engine = TTS() 51 | player = Player() 52 | 53 | scope.launch { 54 | launch { collectConfig() } 55 | 56 | launch { collectAudioFromEngine() } 57 | 58 | try { 59 | engine.run() 60 | } catch (_: CancellationException) { 61 | } catch (e: Throwable) { 62 | resultChannel.send(Result.failure(e)) // tell error occurs. 63 | error("engine run error: $e") 64 | } 65 | } 66 | } 67 | 68 | override fun onDestroy() { 69 | runBlocking { 70 | engine.close() 71 | } 72 | scope.cancel() 73 | super.onDestroy() 74 | } 75 | 76 | override fun onStop() { 77 | player.pause() 78 | } 79 | 80 | private suspend fun collectConfig() { 81 | speakerRepository.getActiveFlow().collect { voice -> 82 | if (voice != null) { 83 | locale = voice.locale 84 | voiceName = voice.name 85 | outputFormat = voice.suggestedCodec 86 | prepared = true 87 | info("use speaker: $voiceName - $locale") 88 | } 89 | } 90 | } 91 | 92 | override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int { 93 | return TextToSpeech.LANG_AVAILABLE 94 | } 95 | 96 | override fun onLoadLanguage(lang: String?, country: String?, variant: String?): Int { 97 | return TextToSpeech.LANG_AVAILABLE 98 | } 99 | 100 | override fun onGetLanguage(): Array { 101 | return arrayOf("", "", "") 102 | } 103 | 104 | private val resultChannel = Channel>() 105 | 106 | private fun collectAudioFromEngine() = scope.launch { 107 | engine.output().transform { frame -> 108 | if (frame.audioCompleted) { 109 | emit(Player.Frame(null, endOfFrame = true)) 110 | return@transform 111 | } 112 | if (frame.textCompleted) { 113 | return@transform 114 | } 115 | emit(Player.Frame(frame.data)) 116 | }.play { 117 | resultChannel.send(Result.success(Unit)) 118 | } 119 | } 120 | 121 | private suspend fun Flow.play(onCompleted: suspend () -> Unit) = player.run(this, onCompleted) 122 | 123 | override fun onSynthesizeText(request: SynthesisRequest?, callback: SynthesisCallback?) { 124 | if (request == null || callback == null || !prepared) { 125 | return 126 | } 127 | 128 | val text = request.charSequenceText.toString() 129 | val pitch = request.pitch - 100 130 | val rate = request.speechRate - 100 131 | 132 | info("start synthesizing text: $text") 133 | 134 | runBlocking { 135 | callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1) 136 | 137 | player.play() 138 | 139 | // 1. input text 140 | val metadata = TTS.AudioMetaData( 141 | locale = locale!!, 142 | voiceName = voiceName!!, 143 | volume = "+0%", 144 | outputFormat = outputFormat!!, 145 | pitch = "${pitch}Hz", 146 | rate = "${rate}%", 147 | ) 148 | try { 149 | engine.input(text, metadata) 150 | } catch (e: Throwable) { 151 | callback.error() 152 | error("synthesize text error: $e") 153 | return@runBlocking 154 | } 155 | 156 | // 2. wait result 157 | for (result in resultChannel) { 158 | when { 159 | result.isSuccess -> { 160 | callback.done() 161 | break 162 | } 163 | 164 | result.isFailure -> { 165 | callback.error() 166 | break 167 | } 168 | } 169 | } 170 | } 171 | } 172 | 173 | private fun debug(message: String) { 174 | Log.d(LOG_NAME, message) 175 | scope.launch { 176 | logRepository.debug(LOG_NAME, message) 177 | } 178 | } 179 | 180 | private fun info(message: String) { 181 | logRepository.info(LOG_NAME, message) 182 | Log.i(LOG_NAME, message) 183 | } 184 | 185 | private fun error(message: String) { 186 | logRepository.error(LOG_NAME, message) 187 | Log.e(LOG_NAME, message) 188 | } 189 | 190 | private val String.description: String 191 | get() { 192 | val size = this.length 193 | return if (size > 10) { 194 | "${this.substring(0, 10)}..." 195 | } else { 196 | this 197 | } 198 | } 199 | } 200 | 201 | -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/ui/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.ui 2 | 3 | import android.os.Bundle 4 | import androidx.activity.ComponentActivity 5 | import androidx.activity.compose.setContent 6 | import androidx.activity.enableEdgeToEdge 7 | import androidx.compose.runtime.CompositionLocalProvider 8 | import androidx.compose.ui.platform.LocalLifecycleOwner 9 | import com.istomyang.edgetss.ui.main.MainContent 10 | import com.istomyang.edgetss.ui.theme.EdgeTSSTheme 11 | 12 | class MainActivity : ComponentActivity() { 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | enableEdgeToEdge() 16 | setContent { 17 | CompositionLocalProvider(LocalLifecycleOwner provides this) { 18 | EdgeTSSTheme { 19 | MainContent() 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/ui/main/LogView.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.ui.main 2 | 3 | import androidx.compose.foundation.layout.Column 4 | import androidx.compose.foundation.layout.fillMaxSize 5 | import androidx.compose.foundation.layout.fillMaxWidth 6 | import androidx.compose.foundation.layout.height 7 | import androidx.compose.foundation.layout.padding 8 | import androidx.compose.foundation.layout.size 9 | import androidx.compose.foundation.lazy.LazyColumn 10 | import androidx.compose.foundation.lazy.items 11 | import androidx.compose.foundation.lazy.rememberLazyListState 12 | import androidx.compose.material.icons.Icons 13 | import androidx.compose.material.icons.filled.BugReport 14 | import androidx.compose.material.icons.filled.CleaningServices 15 | import androidx.compose.material.icons.filled.Description 16 | import androidx.compose.material.icons.filled.FilterAlt 17 | import androidx.compose.material.icons.filled.Menu 18 | import androidx.compose.material.icons.filled.ToggleOff 19 | import androidx.compose.material.icons.filled.ToggleOn 20 | import androidx.compose.material3.BottomAppBar 21 | import androidx.compose.material3.DropdownMenu 22 | import androidx.compose.material3.DropdownMenuItem 23 | import androidx.compose.material3.ExperimentalMaterial3Api 24 | import androidx.compose.material3.MaterialTheme 25 | import androidx.compose.material3.Scaffold 26 | import androidx.compose.material3.Text 27 | import androidx.compose.material3.TopAppBar 28 | import androidx.compose.material3.TopAppBarDefaults.topAppBarColors 29 | import androidx.compose.runtime.Composable 30 | import androidx.compose.runtime.LaunchedEffect 31 | import androidx.compose.runtime.getValue 32 | import androidx.compose.runtime.mutableStateOf 33 | import androidx.compose.runtime.remember 34 | import androidx.compose.runtime.setValue 35 | import androidx.compose.ui.Alignment 36 | import androidx.compose.ui.Modifier 37 | import androidx.compose.ui.unit.dp 38 | import androidx.lifecycle.compose.collectAsStateWithLifecycle 39 | import androidx.lifecycle.viewmodel.compose.viewModel 40 | import com.istomyang.edgetss.data.LogLevel 41 | import com.istomyang.edgetss.ui.main.component.IconButton2 42 | 43 | /** 44 | * LogScreen is a top level [Screen] config for [MainContent]. 45 | */ 46 | val LogScreen = Screen(title = "Log", icon = Icons.Filled.Description) { openDrawer -> 47 | LogContentView(openDrawer) 48 | } 49 | 50 | @OptIn(ExperimentalMaterial3Api::class) 51 | @Composable 52 | private fun LogContentView(openDrawer: () -> Unit) { 53 | val viewModel: LogViewModel = viewModel(factory = LogViewModel.Factory) 54 | 55 | val lines by viewModel.linesUiState.collectAsStateWithLifecycle() 56 | val logOpened by viewModel.logOpened.collectAsStateWithLifecycle() 57 | val logDebugOpened by viewModel.logDebugOpened.collectAsStateWithLifecycle() 58 | 59 | LaunchedEffect(UInt) { 60 | viewModel.loadLogs() 61 | viewModel.collectLogs() 62 | } 63 | 64 | Scaffold( 65 | topBar = { 66 | TopAppBar(colors = topAppBarColors( 67 | containerColor = MaterialTheme.colorScheme.primaryContainer, 68 | titleContentColor = MaterialTheme.colorScheme.primary, 69 | ), title = { 70 | Text(text = "Log") 71 | }, navigationIcon = { 72 | IconButton2("Menu", Icons.Default.Menu) { openDrawer() } 73 | }, actions = { 74 | IconButton2( 75 | "Open Log", 76 | if (logOpened) Icons.Filled.ToggleOn else Icons.Filled.ToggleOff, 77 | modifier = Modifier.size(48.dp), 78 | tint = if (logOpened) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onPrimary 79 | ) { 80 | viewModel.openLog(!logOpened) 81 | } 82 | IconButton2( 83 | "Open Debug", 84 | Icons.Filled.BugReport, 85 | modifier = Modifier.size(32.dp), 86 | tint = if (logDebugOpened) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onPrimary 87 | ) { 88 | viewModel.openDebugLog(!logDebugOpened) 89 | } 90 | }) 91 | }, bottomBar = { 92 | BottomAppBar( 93 | actions = { 94 | IconButton2("Clear", Icons.Default.CleaningServices) { 95 | viewModel.clearLog() 96 | } 97 | FilterView( 98 | options = listOf( 99 | MenuOption("All", "all"), 100 | MenuOption("Info", LogLevel.INFO.name), 101 | MenuOption("Debug", LogLevel.DEBUG.name), 102 | MenuOption("Error", LogLevel.ERROR.name), 103 | ) 104 | ) { 105 | viewModel.setLogLevel(it.value) 106 | } 107 | } 108 | ) 109 | } 110 | ) { innerPadding -> 111 | LogViewer( 112 | modifier = Modifier.padding(innerPadding), 113 | lines = lines 114 | ) 115 | } 116 | } 117 | 118 | //@Preview(showBackground = true) 119 | @Composable 120 | private fun ContentViewPreview() { 121 | LogContentView(openDrawer = {}) 122 | } 123 | 124 | @Composable 125 | private fun LogViewer(modifier: Modifier = Modifier, lines: List) { 126 | val lazyListState = rememberLazyListState() 127 | 128 | LaunchedEffect(lines.size) { 129 | if (lines.size > 1) { 130 | lazyListState.animateScrollToItem(lines.size - 1) 131 | } 132 | } 133 | 134 | LazyColumn( 135 | state = lazyListState, 136 | modifier = modifier 137 | .fillMaxSize() 138 | .padding(14.dp) 139 | ) { 140 | items(lines) { line -> 141 | Text( 142 | text = line, 143 | style = MaterialTheme.typography.bodySmall, 144 | modifier = Modifier 145 | .fillMaxWidth() 146 | .padding(bottom = 5.dp) 147 | ) 148 | } 149 | } 150 | } 151 | 152 | //@Preview(showBackground = true) 153 | @Composable 154 | private fun LogViewerPreview() { 155 | val lines = (0..1000).map { 156 | "2023-01-01 00:00:00.000 [INFO] [Log] Hello, world!" 157 | } 158 | 159 | Column( 160 | modifier = Modifier 161 | .height(300.dp) 162 | .fillMaxWidth(), 163 | horizontalAlignment = Alignment.CenterHorizontally 164 | ) { 165 | LogViewer(lines = lines) 166 | } 167 | } 168 | 169 | @Composable 170 | private fun FilterView( 171 | options: List, 172 | onSelected: (MenuOption) -> Unit, 173 | ) { 174 | var expanded by remember { mutableStateOf(false) } 175 | Column { 176 | IconButton2("Level", Icons.Default.FilterAlt) { 177 | expanded = !expanded 178 | } 179 | DropdownMenu( 180 | expanded = expanded, 181 | onDismissRequest = { expanded = false } 182 | ) { 183 | options.forEach { option -> 184 | DropdownMenuItem( 185 | text = { Text(text = option.title) }, 186 | onClick = { 187 | onSelected(option) 188 | expanded = false 189 | } 190 | ) 191 | } 192 | } 193 | } 194 | } 195 | 196 | private data class MenuOption(val title: String, val value: String) -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/ui/main/LogViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.ui.main 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.lifecycle.ViewModelProvider 5 | import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY 6 | import androidx.lifecycle.viewModelScope 7 | import androidx.lifecycle.viewmodel.initializer 8 | import androidx.lifecycle.viewmodel.viewModelFactory 9 | import com.istomyang.edgetss.data.Log 10 | import com.istomyang.edgetss.data.LogLevel 11 | import com.istomyang.edgetss.data.LogRepository 12 | import com.istomyang.edgetss.data.repositoryLog 13 | import kotlinx.coroutines.cancel 14 | import kotlinx.coroutines.delay 15 | import kotlinx.coroutines.flow.MutableStateFlow 16 | import kotlinx.coroutines.flow.SharingStarted 17 | import kotlinx.coroutines.flow.StateFlow 18 | import kotlinx.coroutines.flow.asStateFlow 19 | import kotlinx.coroutines.flow.stateIn 20 | import kotlinx.coroutines.flow.update 21 | import kotlinx.coroutines.launch 22 | import java.time.Instant 23 | import java.time.LocalDateTime 24 | import java.time.ZoneId 25 | import java.time.format.DateTimeFormatter 26 | 27 | class LogViewModel( 28 | val logRepository: LogRepository, 29 | ) : ViewModel() { 30 | 31 | private val _linesUiState = MutableStateFlow(emptyList()) 32 | val linesUiState: StateFlow> = _linesUiState.asStateFlow() 33 | 34 | private val logLevel = MutableStateFlow("all") 35 | 36 | fun loadLogs() { 37 | viewModelScope.launch { 38 | val levels = getLevels() 39 | val data = logRepository.queryAll(levels) 40 | updateLines(data) 41 | } 42 | } 43 | 44 | fun collectLogs() { 45 | viewModelScope.launch { 46 | while (true) { 47 | delay(1000) 48 | val o = _linesUiState.value.count() 49 | val levels = getLevels() 50 | val data = logRepository.query(levels, o, 50) 51 | updateLines(data) 52 | } 53 | } 54 | } 55 | 56 | private fun getLevels(): List { 57 | return if (logLevel.value == "all") { 58 | listOf(LogLevel.INFO.name, LogLevel.DEBUG.name, LogLevel.ERROR.name) 59 | } else { 60 | listOf(logLevel.value) 61 | } 62 | } 63 | 64 | private fun updateLines(newLines: List) { 65 | _linesUiState.update { it + newLines.map { log -> "${ts2DateTime(log.createdAt)} ${log.level} ${log.domain}: ${log.message}" } } 66 | } 67 | 68 | fun setLogLevel(level: String) { 69 | logLevel.value = level 70 | _linesUiState.update { emptyList() } // clear screen. 71 | loadLogs() 72 | } 73 | 74 | fun openLog(b: Boolean) { 75 | viewModelScope.launch { 76 | logRepository.open(b) 77 | } 78 | } 79 | 80 | fun openDebugLog(b: Boolean) { 81 | viewModelScope.launch { 82 | logRepository.openDebug(b) 83 | } 84 | } 85 | 86 | fun clearLog() { 87 | viewModelScope.launch { 88 | _linesUiState.update { emptyList() } 89 | logRepository.clear() 90 | } 91 | } 92 | 93 | val logOpened: StateFlow = logRepository.enabled.stateIn( 94 | scope = viewModelScope, 95 | started = SharingStarted.WhileSubscribed(), 96 | initialValue = false 97 | ) 98 | 99 | val logDebugOpened: StateFlow = logRepository.enabledDebug.stateIn( 100 | scope = viewModelScope, 101 | started = SharingStarted.WhileSubscribed(), 102 | initialValue = false 103 | ) 104 | 105 | override fun onCleared() { 106 | super.onCleared() 107 | viewModelScope.cancel() 108 | } 109 | 110 | private fun ts2DateTime(ts: Long): String { 111 | return LocalDateTime.ofInstant( 112 | Instant.ofEpochMilli(ts), 113 | ZoneId.systemDefault() 114 | ).format( 115 | DateTimeFormatter.ofPattern("MM-dd-HH:mm:ss") 116 | ) 117 | } 118 | 119 | companion object { 120 | val Factory: ViewModelProvider.Factory = viewModelFactory { 121 | initializer { 122 | val context = this[APPLICATION_KEY]!!.applicationContext 123 | LogViewModel(context.repositoryLog) 124 | } 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/ui/main/MainView.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.ui.main 2 | 3 | import androidx.compose.foundation.layout.Column 4 | import androidx.compose.foundation.layout.Spacer 5 | import androidx.compose.foundation.layout.height 6 | import androidx.compose.foundation.layout.padding 7 | import androidx.compose.foundation.rememberScrollState 8 | import androidx.compose.foundation.verticalScroll 9 | import androidx.compose.material3.DrawerValue 10 | import androidx.compose.material3.Icon 11 | import androidx.compose.material3.ModalDrawerSheet 12 | import androidx.compose.material3.ModalNavigationDrawer 13 | import androidx.compose.material3.NavigationDrawerItem 14 | import androidx.compose.material3.NavigationDrawerItemDefaults 15 | import androidx.compose.material3.Text 16 | import androidx.compose.material3.rememberDrawerState 17 | import androidx.compose.runtime.Composable 18 | import androidx.compose.runtime.mutableStateOf 19 | import androidx.compose.runtime.remember 20 | import androidx.compose.runtime.rememberCoroutineScope 21 | import androidx.compose.ui.Modifier 22 | import androidx.compose.ui.graphics.vector.ImageVector 23 | import androidx.compose.ui.tooling.preview.Preview 24 | import androidx.compose.ui.unit.dp 25 | import kotlinx.coroutines.launch 26 | 27 | 28 | /** 29 | * Screen defines a item for [ModalNavigationDrawer] in [MainContent]. 30 | */ 31 | data class Screen( 32 | val title: String, 33 | val icon: ImageVector, 34 | val makeContent: @Composable (openDrawer: () -> Unit) -> Unit 35 | ) 36 | 37 | @Composable 38 | fun MainContent() { 39 | val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) 40 | val scope = rememberCoroutineScope() 41 | 42 | val screens: List = listOf(SpeakerScreen, LogScreen) 43 | val selectedScreen = remember { mutableStateOf(screens[0]) } 44 | 45 | // The reason I don't use [NavigationBar] is that [Scaffold] needs to be in the parent 46 | // layer, which breaks the connection between [TopAppBar] and [ContentView], 47 | // which is a complex but not necessary design. 48 | // In this app, Speaker is a main and unique part, and [NavigationBar] which I think is 49 | // putting equally important part in a one layer. Based on this, I think complex sibling 50 | // component interactions are necessary. 51 | ModalNavigationDrawer( 52 | drawerState = drawerState, 53 | drawerContent = { 54 | ModalDrawerSheet { 55 | Column(Modifier.verticalScroll(rememberScrollState())) { 56 | Spacer(Modifier.height(12.dp)) 57 | screens.forEach { screen -> 58 | NavigationDrawerItem( 59 | icon = { Icon(screen.icon, contentDescription = null) }, 60 | label = { Text(screen.title) }, 61 | selected = false, 62 | onClick = { 63 | scope.launch { drawerState.close() } 64 | selectedScreen.value = screen 65 | }, 66 | modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding) 67 | ) 68 | } 69 | } 70 | } 71 | }, 72 | ) { 73 | selectedScreen.value.makeContent { scope.launch { drawerState.open() } } 74 | } 75 | } 76 | 77 | 78 | @Preview(showBackground = true) 79 | @Composable 80 | fun MainContentPreview() { 81 | MainContent() 82 | } -------------------------------------------------------------------------------- /app/src/main/java/com/istomyang/edgetss/ui/main/SpeakerView.kt: -------------------------------------------------------------------------------- 1 | package com.istomyang.edgetss.ui.main 2 | 3 | import android.util.Log 4 | import androidx.compose.foundation.Image 5 | import androidx.compose.foundation.clickable 6 | import androidx.compose.foundation.layout.Arrangement 7 | import androidx.compose.foundation.layout.Column 8 | import androidx.compose.foundation.layout.Row 9 | import androidx.compose.foundation.layout.Spacer 10 | import androidx.compose.foundation.layout.fillMaxWidth 11 | import androidx.compose.foundation.layout.heightIn 12 | import androidx.compose.foundation.layout.padding 13 | import androidx.compose.foundation.layout.size 14 | import androidx.compose.foundation.lazy.LazyColumn 15 | import androidx.compose.foundation.lazy.items 16 | import androidx.compose.foundation.shape.RoundedCornerShape 17 | import androidx.compose.material.icons.Icons 18 | import androidx.compose.material.icons.filled.Add 19 | import androidx.compose.material.icons.filled.Check 20 | import androidx.compose.material.icons.filled.Close 21 | import androidx.compose.material.icons.filled.Delete 22 | import androidx.compose.material.icons.filled.Edit 23 | import androidx.compose.material.icons.filled.Female 24 | import androidx.compose.material.icons.filled.Male 25 | import androidx.compose.material.icons.filled.Menu 26 | import androidx.compose.material.icons.filled.RadioButtonChecked 27 | import androidx.compose.material.icons.filled.RadioButtonUnchecked 28 | import androidx.compose.material.icons.filled.RecentActors 29 | import androidx.compose.material.icons.filled.Search 30 | import androidx.compose.material3.Card 31 | import androidx.compose.material3.Checkbox 32 | import androidx.compose.material3.CircularProgressIndicator 33 | import androidx.compose.material3.ExperimentalMaterial3Api 34 | import androidx.compose.material3.HorizontalDivider 35 | import androidx.compose.material3.Icon 36 | import androidx.compose.material3.ListItem 37 | import androidx.compose.material3.LocalContentColor 38 | import androidx.compose.material3.MaterialTheme 39 | import androidx.compose.material3.Scaffold 40 | import androidx.compose.material3.SnackbarHost 41 | import androidx.compose.material3.SnackbarHostState 42 | import androidx.compose.material3.Text 43 | import androidx.compose.material3.TextButton 44 | import androidx.compose.material3.TextField 45 | import androidx.compose.material3.TopAppBar 46 | import androidx.compose.material3.TopAppBarDefaults.topAppBarColors 47 | import androidx.compose.runtime.Composable 48 | import androidx.compose.runtime.LaunchedEffect 49 | import androidx.compose.runtime.getValue 50 | import androidx.compose.runtime.mutableStateListOf 51 | import androidx.compose.runtime.mutableStateOf 52 | import androidx.compose.runtime.remember 53 | import androidx.compose.runtime.rememberCoroutineScope 54 | import androidx.compose.runtime.setValue 55 | import androidx.compose.ui.Alignment 56 | import androidx.compose.ui.Modifier 57 | import androidx.compose.ui.tooling.preview.Preview 58 | import androidx.compose.ui.unit.dp 59 | import androidx.compose.ui.window.Dialog 60 | import androidx.compose.ui.window.DialogProperties 61 | import androidx.lifecycle.compose.collectAsStateWithLifecycle 62 | import androidx.lifecycle.viewmodel.compose.viewModel 63 | import com.istomyang.edgetss.ui.main.component.IconButton2 64 | import com.istomyang.tts_engine.SpeakerManager 65 | import kotlinx.coroutines.launch 66 | 67 | /** 68 | * SpeakerScreen is a top level [Screen] config for [MainContent]. 69 | */ 70 | val SpeakerScreen = Screen(title = "Speaker", icon = Icons.Filled.RecentActors) { openDrawer -> 71 | SpeakerContentView(openDrawer) 72 | } 73 | 74 | @OptIn(ExperimentalMaterial3Api::class) 75 | @Composable 76 | private fun SpeakerContentView(openDrawer: () -> Unit) { 77 | val viewModel: SpeakerViewModel = viewModel(factory = SpeakerViewModel.Factory) 78 | 79 | val speakers by viewModel.speakerUiState.collectAsStateWithLifecycle() 80 | val voices by viewModel.voicesUiState.collectAsStateWithLifecycle() 81 | val message by viewModel.messageUiState.collectAsStateWithLifecycle() 82 | val settings by viewModel.settingsUiState.collectAsStateWithLifecycle() 83 | 84 | var openPicker by remember { mutableStateOf(false) } 85 | var editMode by remember { mutableStateOf(false) } 86 | val editItems = remember { mutableStateListOf() } // id 87 | 88 | var openSetting by remember { mutableStateOf(false) } 89 | 90 | val scope = rememberCoroutineScope() 91 | val snackBarHostState = remember { SnackbarHostState() } 92 | 93 | LaunchedEffect(message) { 94 | scope.launch { 95 | val message = message ?: return@launch 96 | val msg = if (message.error) { 97 | "Error: ${message.description}" 98 | } else { 99 | message.description 100 | } 101 | snackBarHostState.showSnackbar(message = msg) 102 | } 103 | } 104 | 105 | Scaffold( 106 | snackbarHost = { 107 | SnackbarHost(hostState = snackBarHostState) 108 | }, 109 | topBar = { 110 | TopAppBar(colors = topAppBarColors( 111 | containerColor = MaterialTheme.colorScheme.primaryContainer, 112 | titleContentColor = MaterialTheme.colorScheme.primary, 113 | ), title = { 114 | Text(text = "Edge TSS") 115 | }, navigationIcon = { 116 | IconButton2("Menu", Icons.Default.Menu) { openDrawer() } 117 | }, actions = { 118 | when (editMode) { 119 | true -> { 120 | Text("${editItems.size} selected") 121 | IconButton2( 122 | "Delete", Icons.Filled.Delete 123 | ) { 124 | viewModel.removeSpeakers(editItems) 125 | } 126 | IconButton2("Cancel", Icons.Filled.Close) { 127 | editMode = false 128 | editItems.clear() 129 | } 130 | } 131 | false -> { 132 | // IconButton2("Open Settings", Icons.Filled.Settings) { 133 | // openSetting = true 134 | // } 135 | IconButton2("Add Items", Icons.Filled.Add) { 136 | openPicker = true 137 | viewModel.loadVoices() 138 | } 139 | IconButton2("Edit Items", Icons.Filled.Edit) { 140 | editMode = true 141 | } 142 | } 143 | } 144 | }) 145 | }, 146 | ) { innerPadding -> 147 | LazyColumn( 148 | modifier = Modifier.padding(innerPadding), 149 | verticalArrangement = Arrangement.spacedBy(5.dp), 150 | ) { 151 | items(speakers) { speaker -> 152 | Item(speaker = speaker, 153 | status = if (editMode) ItemStatus.EDIT else ItemStatus.VIEW, 154 | onSelected = { id -> 155 | when (editMode) { 156 | true -> { 157 | if (editItems.contains(id)) { 158 | editItems.remove(id) 159 | } else { 160 | editItems.add(id) 161 | } 162 | } 163 | false -> { 164 | viewModel.setActiveSpeaker(id) 165 | } 166 | } 167 | }) 168 | } 169 | } 170 | } 171 | 172 | if (openPicker) { 173 | SpeakerPicker( 174 | data = voices, 175 | onConfirm = { ids -> 176 | openPicker = false 177 | viewModel.addSpeakers(ids) 178 | }, 179 | onCancel = { 180 | openPicker = false 181 | } 182 | ) 183 | } 184 | 185 | if (openSetting) { 186 | Settings( 187 | defaultValue = settings, 188 | onConfirm = { 189 | openSetting = false 190 | viewModel.setAudioFormat(it.format) 191 | }, 192 | onCancel = { 193 | openSetting = false 194 | } 195 | ) 196 | } 197 | } 198 | 199 | //@Preview(showBackground = true) 200 | @Composable 201 | private fun ContentViewPreview() { 202 | SpeakerContentView {} 203 | } 204 | 205 | // region ListItem 206 | 207 | private enum class ItemStatus { 208 | VIEW, EDIT 209 | } 210 | 211 | @Composable 212 | private fun Item(speaker: Speaker, status: ItemStatus, onSelected: (id: String) -> Unit) { 213 | var selected by remember { mutableStateOf(false) } 214 | var preMode by remember { mutableStateOf(status) } 215 | 216 | if (preMode != status) { 217 | preMode = status 218 | selected = false 219 | } 220 | 221 | ListItem(modifier = Modifier.clickable { 222 | selected = !selected 223 | onSelected(speaker.id) 224 | }, 225 | headlineContent = { Text(speaker.name) }, 226 | supportingContent = { Text(speaker.description) }, 227 | trailingContent = { Text(speaker.locale) }, 228 | leadingContent = { 229 | when (status) { 230 | ItemStatus.VIEW -> { 231 | Icon( 232 | if (speaker.active) Icons.Filled.Check else if (speaker.gender == "Male") Icons.Filled.Male else Icons.Filled.Female, 233 | contentDescription = "", 234 | tint = if (selected) MaterialTheme.colorScheme.primary else LocalContentColor.current 235 | ) 236 | } 237 | 238 | ItemStatus.EDIT -> { 239 | Icon( 240 | if (selected) Icons.Filled.RadioButtonChecked else Icons.Filled.RadioButtonUnchecked, 241 | contentDescription = "", 242 | tint = MaterialTheme.colorScheme.primary 243 | ) 244 | } 245 | } 246 | }) 247 | } 248 | 249 | // endregion 250 | 251 | // region SpeakerPicker 252 | 253 | data class Option(val title: String, val value: String, val searchKey: String) 254 | 255 | @Composable 256 | private fun SpeakerPicker( 257 | modifier: Modifier = Modifier, 258 | data: List