├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── 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
│ │ │ │ ├── themes.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── font_certs.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ └── drawable
│ │ │ │ ├── ic_play_white.xml
│ │ │ │ ├── ic_pause.xml
│ │ │ │ ├── ic_skip_previous.xml
│ │ │ │ ├── ic_skip_next.xml
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── app
│ │ │ │ └── autohighlighttts
│ │ │ │ ├── AppApplication.kt
│ │ │ │ ├── ui
│ │ │ │ └── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── AutoHighlightTTSViewModel.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── AutoHighlightTTSScreen.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── app
│ │ │ └── autohighlighttts
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── app
│ │ └── autohighlighttts
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── AutoHighlightTTS
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── app
│ │ │ └── autohighlighttts
│ │ │ ├── models
│ │ │ └── ParagraphModel.kt
│ │ │ ├── AutoHighlightTTSHelper.kt
│ │ │ ├── composable
│ │ │ └── AutoHighlightTTS.kt
│ │ │ ├── AutoHighlightTTSComposable.kt
│ │ │ └── AutoHighlightTTSEngine.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── app
│ │ │ └── autohighlighttts
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── app
│ │ └── autohighlighttts
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── media
└── img.png
├── jitpack.yml
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── settings.gradle.kts
├── LICENSE
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── gradlew
└── README.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/AutoHighlightTTS/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/AutoHighlightTTS/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/media/img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/media/img.png
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
3 | before_install:
4 | - sdk install java 17.0.13-open
5 | - sdk use java 17.0.13-open
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/AutoHighlightTTS/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/AppApplication.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 |
7 | @HiltAndroidApp
8 | class AppApplication : Application()
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/java/com/app/autohighlighttts/models/ParagraphModel.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts.models
2 |
3 | data class ParagraphModel(
4 | val text: String,
5 | val totalWordOfText: Int,
6 | val startIndex: Int,
7 | val endIndex: Int,
8 | )
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Feb 20 15:47:59 IST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
12 | val Amaranth = Color(0xFFED184F)
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "MITextToSpeech"
17 | include(":app")
18 | include(":AutoHighlightTTS")
19 |
--------------------------------------------------------------------------------
/app/src/test/java/com/app/autohighlighttts/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/test/java/com/app/autohighlighttts/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_play_white.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | MITextToSpeech
3 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Let reset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
4 | Text-To-Speech
5 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/app/autohighlighttts/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
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.app.mitexttospeech", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/androidTest/java/com/app/autohighlighttts/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
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.app.mitexttospeech.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/AutoHighlightTTS/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/main/res/drawable/ic_pause.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_skip_previous.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/AutoHighlightTTSViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.content.Context
4 | import androidx.lifecycle.ViewModel
5 | import dagger.hilt.android.lifecycle.HiltViewModel
6 | import dagger.hilt.android.qualifiers.ApplicationContext
7 | import java.util.Locale
8 | import javax.inject.Inject
9 | import com.app.autohighlightttssample.R
10 |
11 | @HiltViewModel
12 | class AutoHighlightTTSViewModel @Inject constructor(@ApplicationContext context: Context) : ViewModel() {
13 |
14 | lateinit var instanceOfTTS: AutoHighlightTTSEngine
15 |
16 | init {
17 | initTTS(context)
18 | }
19 |
20 | private fun initTTS(context: Context): AutoHighlightTTSEngine {
21 | instanceOfTTS = AutoHighlightTTSEngine
22 | .getInstance()
23 | .init(context)
24 | .setLanguage(Locale.ENGLISH)
25 | .setPitchAndSpeed(1f, 1f)
26 | .setText(context.getString(R.string.text_to_speech_text))
27 | return instanceOfTTS
28 | }
29 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.foundation.layout.fillMaxSize
7 | import androidx.compose.material3.MaterialTheme
8 | import androidx.compose.material3.Surface
9 | import androidx.compose.ui.Modifier
10 | import com.app.autohighlighttts.ui.theme.MITextToSpeechTheme
11 | import dagger.hilt.android.AndroidEntryPoint
12 |
13 | @AndroidEntryPoint
14 | class MainActivity : ComponentActivity() {
15 | override fun onCreate(savedInstanceState: Bundle?) {
16 | super.onCreate(savedInstanceState)
17 | setContent {
18 | MITextToSpeechTheme {
19 | Surface(
20 | modifier = Modifier.fillMaxSize(),
21 | color = MaterialTheme.colorScheme.background
22 | ) {
23 | TTSScreen()
24 | }
25 | }
26 | }
27 | }
28 | }
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_skip_next.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
14 |
15 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Mindinventory
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
16 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontStyle
7 | import androidx.compose.ui.text.font.FontWeight
8 | import androidx.compose.ui.text.googlefonts.Font
9 | import androidx.compose.ui.text.googlefonts.GoogleFont
10 | import androidx.compose.ui.unit.sp
11 | import com.app.autohighlighttts.R
12 |
13 |
14 | val fontName = GoogleFont("Kanit")
15 |
16 | val provider = GoogleFont.Provider(
17 | providerAuthority = "com.google.android.gms.fonts",
18 | providerPackage = "com.google.android.gms",
19 | certificates = com.app.autohighlightttssample.R.array.com_google_android_gms_fonts_certs
20 | )
21 |
22 |
23 | val fontFamily = FontFamily(
24 | Font(
25 | googleFont = fontName,
26 | fontProvider = provider,
27 | weight = FontWeight.Bold,
28 | style = FontStyle.Italic
29 | )
30 | )
31 |
32 | // Set of Material typography styles to start with
33 | val Typography = Typography(
34 | bodyLarge = TextStyle(
35 | fontFamily = FontFamily.Default,
36 | fontWeight = FontWeight.Normal,
37 | fontSize = 16.sp,
38 | lineHeight = 24.sp,
39 | letterSpacing = 0.5.sp
40 | )
41 | )
42 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/AutoHighlightTTS/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.library)
3 | alias(libs.plugins.kotlin.android)
4 | alias(libs.plugins.compose.compiler)
5 | id("maven-publish")
6 | }
7 |
8 | android {
9 | namespace = "com.app.autohighlighttts"
10 | compileSdk = libs.versions.compileSdk.get().toInt()
11 |
12 | defaultConfig {
13 | minSdk = libs.versions.minSdk.get().toInt()
14 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
15 | consumerProguardFiles("consumer-rules.pro")
16 | }
17 |
18 | buildTypes {
19 | release {
20 | isMinifyEnabled = false
21 | proguardFiles(
22 | getDefaultProguardFile("proguard-android-optimize.txt"),
23 | "proguard-rules.pro"
24 | )
25 | }
26 | }
27 |
28 | buildFeatures {
29 | compose = true
30 | }
31 |
32 | compileOptions {
33 | sourceCompatibility = JavaVersion.VERSION_17
34 | targetCompatibility = JavaVersion.VERSION_17
35 | }
36 | kotlinOptions {
37 | jvmTarget = "17"
38 | }
39 | }
40 |
41 | publishing {
42 | publications {
43 | register("release") {
44 | afterEvaluate {
45 | from(components["release"])
46 | }
47 | }
48 | }
49 | }
50 |
51 | dependencies {
52 | with(libs) {
53 |
54 | implementation(core.ktx)
55 | implementation(appcompat)
56 | testImplementation(junit)
57 | androidTestImplementation(androidx.junit)
58 | androidTestImplementation(espresso.core)
59 |
60 | with(compose){
61 | implementation(platform(bom))
62 | implementation(ui)
63 | implementation(ui.graphics)
64 | implementation(ui.tooling.preview)
65 | implementation(material3)
66 | }
67 | }
68 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 | )
29 |
30 | @Composable
31 | fun MITextToSpeechTheme(
32 | darkTheme: Boolean = isSystemInDarkTheme(),
33 | // Dynamic color is available on Android 12+
34 | dynamicColor: Boolean = true,
35 | content: @Composable () -> Unit
36 | ) {
37 | val colorScheme = when {
38 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
39 | val context = LocalContext.current
40 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
41 | }
42 |
43 | darkTheme -> DarkColorScheme
44 | else -> LightColorScheme
45 | }
46 | val view = LocalView.current
47 | if (!view.isInEditMode) {
48 | SideEffect {
49 | val window = (view.context as Activity).window
50 | window.statusBarColor = colorScheme.primary.toArgb()
51 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
52 | }
53 | }
54 |
55 | MaterialTheme(
56 | colorScheme = colorScheme,
57 | typography = Typography,
58 | content = content
59 | )
60 | }
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/java/com/app/autohighlighttts/AutoHighlightTTSHelper.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.os.Bundle
4 | import android.speech.tts.TextToSpeech
5 |
6 |
7 | /**
8 | * [play] Extension Function for Play The TTS.
9 | */
10 | internal fun TextToSpeech.play(
11 | text: String,
12 | queueMode: Int
13 | = TextToSpeech.QUEUE_FLUSH,
14 | params: Bundle? = null,
15 | utteranceId: String = TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED
16 | ) {
17 | speak(text, queueMode, params, utteranceId)
18 | }
19 |
20 | /**
21 | * [getStartAndEndOfSubstring] Function is give the start & end form this String
22 | */
23 | internal fun getStartAndEndOfSubstring(str: String, sub: String): Pair {
24 | val start = str.indexOf(sub)
25 | return when (start != -1) {
26 | true -> Pair(start, start + sub.length)
27 | false -> Pair(-1, -1)
28 | }
29 | }
30 |
31 | /**
32 | * [countWords] this function is return the count/length of string total words.
33 | */
34 | internal fun countWords(paragraph: String): Int {
35 | // Split the paragraph into words using regular expression and count the number of words
36 | return paragraph.trim().split(" ").size
37 | }
38 |
39 | /**
40 | * Calculates the percentage of a slider's position within a range.
41 | *
42 | * This function computes the percentage of the slider's position relative to the range
43 | * defined by the start and end indices.
44 | *
45 | * @param start The starting index of the range.
46 | * @param end The ending index of the range.
47 | * @param sliderPosition The current position of the slider within the range.
48 | * @return The percentage of the slider's position within the range.
49 | */
50 | internal fun calculatePercentage(start: Int, end: Int, sliderPosition: Int): Double {
51 | // Calculate the total number of positions in the range
52 | val totalNumbers = end - start + 1
53 | // Calculate the position of the slider relative to the start index
54 | val sliderRelativeToStart = sliderPosition - start + 1
55 | // Calculate the percentage of the slider's position within the range
56 | return (sliderRelativeToStart.toDouble() / totalNumbers.toDouble()) * 100
57 | }
58 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Android ###
2 | # Built application files
3 | *.apk
4 | *.ap_
5 | *.aab
6 |
7 | # Files for the ART/Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 | out/
17 |
18 | # Gradle files
19 | .gradle/
20 | build/
21 |
22 | # Local configuration file (sdk path, etc)
23 | local.properties
24 |
25 | # Proguard folder generated by Eclipse
26 | proguard/
27 |
28 | # Log Files
29 | *.log
30 |
31 | # Android Studio Navigation editor temp files
32 | .navigation/
33 |
34 | # Android Studio captures folder
35 | captures/
36 |
37 | # IntelliJ
38 | *.iml
39 | *.idea
40 |
41 | # Keystore files
42 | # Uncomment the following lines if you do not want to check your keystore files in.
43 | #*.jks
44 | #*.keystore
45 |
46 | # External native build folder generated in Android Studio 2.2 and later
47 | .externalNativeBuild
48 |
49 | # Freeline
50 | freeline.py
51 | freeline/
52 | freeline_project_description.json
53 |
54 | # fastlane
55 | fastlane/report.xml
56 | fastlane/Preview.html
57 | fastlane/screenshots
58 | fastlane/test_output
59 | fastlane/readme.md
60 |
61 | # lint
62 | lint/intermediates/
63 | lint/generated/
64 | lint/outputs/
65 | lint/tmp/
66 | # lint/reports/
67 |
68 | ### AndroidStudio ###
69 | # Covers files to be ignored for android development using Android Studio.
70 |
71 | # Signing files
72 | .signing/
73 |
74 | # Local configuration file (sdk path, etc)
75 |
76 | # Proguard folder generated by Eclipse
77 |
78 | # Log Files
79 |
80 | # Android Patch
81 |
82 | # External native build folder generated in Android Studio 2.2 and later
83 |
84 | # NDK
85 | obj/
86 |
87 | # IntelliJ IDEA
88 | *.iws
89 | /out/
90 |
91 | # OS-specific files
92 | .DS_Store
93 | .DS_Store?
94 | ._*
95 | .Spotlight-V100
96 | .Trashes
97 | ehthumbs.db
98 | Thumbs.db
99 |
100 | # Legacy Eclipse project files
101 | .classpath
102 | .project
103 | .cproject
104 | .settings/
105 |
106 | # Mobile Tools for Java (J2ME)
107 | .mtj.tmp/
108 |
109 | # Package Files #
110 | *.war
111 | *.ear
112 |
113 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
114 | hs_err_pid*
115 |
116 | # Package Files #
117 | *.nar
118 | *.zip
119 | *.tar.gz
120 | *.rar
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.kotlin.android)
4 | alias(libs.plugins.kotlinAndroidKsp)
5 | alias(libs.plugins.hilt.android)
6 | alias(libs.plugins.compose.compiler)
7 | }
8 |
9 | android {
10 | namespace = "com.app.autohighlightttssample"
11 | compileSdk = libs.versions.compileSdk.get().toInt()
12 |
13 | defaultConfig {
14 | applicationId = "com.app.mitexttospeechsample"
15 | minSdk = libs.versions.minSdk.get().toInt()
16 | targetSdk = libs.versions.targetSdk.get().toInt()
17 | versionCode = 1
18 | versionName = "1.0"
19 |
20 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
21 | vectorDrawables {
22 | useSupportLibrary = true
23 | }
24 | }
25 |
26 | buildTypes {
27 | release {
28 | isMinifyEnabled = false
29 | proguardFiles(
30 | getDefaultProguardFile("proguard-android-optimize.txt"),
31 | "proguard-rules.pro"
32 | )
33 | }
34 | }
35 | compileOptions {
36 | sourceCompatibility = JavaVersion.VERSION_17
37 | targetCompatibility = JavaVersion.VERSION_17
38 | }
39 | kotlinOptions {
40 | jvmTarget = "17"
41 | }
42 | buildFeatures {
43 | compose = true
44 | }
45 | packaging {
46 | resources {
47 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
48 | }
49 | }
50 | }
51 |
52 | dependencies {
53 | with(libs){
54 |
55 | with(compose){
56 | implementation(platform(bom))
57 | implementation(ui)
58 | implementation(ui.graphics)
59 | implementation(ui.tooling.preview)
60 | implementation(ui.text.google.fonts)
61 | }
62 |
63 | implementation(core.ktx)
64 | implementation(lifecycle.runtime.ktx)
65 | implementation(activity.compose)
66 | implementation(material3)
67 |
68 | testImplementation(junit)
69 | androidTestImplementation(androidx.junit)
70 | androidTestImplementation(espresso.core)
71 | debugImplementation(ui.tooling)
72 | debugImplementation(ui.test.manifest)
73 |
74 | // MITextToSpeech Library
75 | implementation(project(":AutoHighlightTTS"))
76 |
77 | // Hilt dependencies
78 | with(hilt){
79 | implementation(android)
80 | ksp(android.compiler)
81 | ksp(compiler)
82 | implementation(navigation.compose)
83 | }
84 | }
85 | }
86 |
87 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | kotlin = "2.1.0"
3 | compileSdk = "35"
4 | minSdk = "24"
5 | targetSdk = "35"
6 | junit = "4.13.2"
7 | coreKtx = "1.15.0"
8 | lifecycleRuntimeKtx = "2.8.7"
9 | activityCompose = "1.9.3"
10 | composeBom = "2024.12.01"
11 | hiltAndroid = "2.51.1"
12 | hiltNavigationCompose = "1.2.0"
13 | hiltJetpackCompiler = "1.2.0"
14 | espresso = "3.6.1"
15 | junitExt = "1.2.1"
16 | hiltPlugin = "2.49"
17 | androidGradlePlugin = "8.6.1"
18 | kspVersion = "2.1.0-1.0.29"
19 | appCompat = "1.7.0"
20 | material = "1.12.0"
21 |
22 | [libraries]
23 | core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
24 | lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
25 | activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
26 | compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
27 | compose-ui = { group = "androidx.compose.ui", name = "ui" }
28 | compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
29 | compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
30 | material3 = { group = "androidx.compose.material3", name = "material3"}
31 | compose-ui-text-google-fonts = { group = "androidx.compose.ui", name = "ui-text-google-fonts"}
32 | junit = { group = "junit", name = "junit", version.ref = "junit" }
33 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitExt" }
34 | espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso" }
35 | ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
36 | ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
37 | hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hiltAndroid" }
38 | hilt-android-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hiltAndroid" }
39 | hilt-navigation-compose = { group = "androidx.hilt", name = "hilt-navigation-compose", version.ref = "hiltNavigationCompose" }
40 | hilt-compiler = { group = "androidx.hilt", name = "hilt-compiler", version.ref = "hiltJetpackCompiler" }
41 | appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appCompat" }
42 | material = { group = "com.google.android.material", name = "material", version.ref = "material" }
43 |
44 | [plugins]
45 | android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }
46 | android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
47 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
48 | hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hiltPlugin" }
49 | kotlinAndroidKsp = { id = "com.google.devtools.ksp", version.ref ="kspVersion" }
50 | compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
51 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/java/com/app/autohighlighttts/composable/AutoHighlightTTS.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts.composable
2 |
3 | import androidx.compose.foundation.text.InlineTextContent
4 | import androidx.compose.material3.LocalTextStyle
5 | import androidx.compose.material3.Text
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.ui.Modifier
8 | import androidx.compose.ui.graphics.Color
9 | import androidx.compose.ui.text.SpanStyle
10 | import androidx.compose.ui.text.TextLayoutResult
11 | import androidx.compose.ui.text.TextStyle
12 | import androidx.compose.ui.text.buildAnnotatedString
13 | import androidx.compose.ui.text.font.FontFamily
14 | import androidx.compose.ui.text.font.FontStyle
15 | import androidx.compose.ui.text.font.FontWeight
16 | import androidx.compose.ui.text.style.TextAlign
17 | import androidx.compose.ui.text.style.TextDecoration
18 | import androidx.compose.ui.text.style.TextOverflow
19 | import androidx.compose.ui.unit.TextUnit
20 | import androidx.compose.ui.unit.sp
21 |
22 |
23 |
24 | /**
25 | * This is a custom text that can highlight the text
26 | * @param autoHighlightTTSBuilder: TextHighlightBuilder
27 | */
28 | @Composable
29 | internal fun AutoHighlightTTS(
30 | autoHighlightTTSBuilder: AutoHighlightTTSBuilder,
31 | modifier: Modifier = Modifier,
32 | color: Color = Color.Unspecified,
33 | fontSize: TextUnit = TextUnit.Unspecified,
34 | fontStyle: FontStyle? = null,
35 | fontWeight: FontWeight? = null,
36 | fontFamily: FontFamily? = null,
37 | letterSpacing: TextUnit = TextUnit.Unspecified,
38 | textDecoration: TextDecoration? = null,
39 | textAlign: TextAlign? = null,
40 | lineHeight: TextUnit = TextUnit.Unspecified,
41 | overflow: TextOverflow = TextOverflow.Clip,
42 | softWrap: Boolean = true,
43 | maxLines: Int = Int.MAX_VALUE,
44 | minLines: Int = 1,
45 | inlineContent: Map = mapOf(),
46 | onTextLayout: (TextLayoutResult) -> Unit = {},
47 | style: TextStyle = LocalTextStyle.current
48 |
49 | ) {
50 | Text(
51 | modifier = modifier,
52 | text = autoHighlightTTSBuilder.annotatedString,
53 | color = color,
54 | fontSize = fontSize,
55 | fontStyle = fontStyle,
56 | fontWeight = fontWeight,
57 | fontFamily = fontFamily,
58 | letterSpacing = letterSpacing,
59 | textDecoration = textDecoration,
60 | textAlign = textAlign,
61 | lineHeight = lineHeight,
62 | overflow = overflow,
63 | softWrap = softWrap,
64 | maxLines = maxLines,
65 | minLines= minLines,
66 | inlineContent = inlineContent,
67 | onTextLayout = onTextLayout,
68 | style = style,
69 | )
70 | }
71 |
72 | /**
73 | * This is a builder class that can highlight the text
74 | * @param text: String
75 | * @param startEnd: Pair
76 | */
77 | data class AutoHighlightTTSBuilder(
78 | val text: String,
79 | val startEnd: Pair,
80 | val style: SpanStyle = SpanStyle(
81 | color = Color.Black,
82 | fontWeight = FontWeight.Bold,
83 | fontSize = 14.sp
84 | )
85 | ) {
86 | val annotatedString = buildAnnotatedString {
87 | // Append the text and highlight the start and end with old text to black
88 | append(text)
89 | addStyle(
90 | style = style,
91 | start = startEnd.first,
92 | end = startEnd.second
93 | )
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/app/src/main/res/values/font_certs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - @array/com_google_android_gms_fonts_certs_dev
5 | - @array/com_google_android_gms_fonts_certs_prod
6 |
7 |
8 | -
9 | MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAeFw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVyxW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8XW8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexAcKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkwHQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0cxb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrPzgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXclaXjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05aIskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+aayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUWEv9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs=
10 |
11 |
12 |
13 | -
14 | MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDAeFw0wODA4MjEyMzEzMzRaFw0zNjAxMDcyMzEzMzRaMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBAKtWLgDYO6IIrgqWbxJOKdoR8qtW0I9Y4sypEwPpt1TTcvZApxsdyxMJZ2JORland2qSGT2y5b+3JKkedxiLDmpHpDsz2WCbdxgxRczfey5YZnTJ4VZbH0xqWVW/8lGmPav5xVwnIiJS6HXk+BVKZF+JcWjAsb/GEuq/eFdpuzSqeYTcfi6idkyugwfYwXFU1+5fZKUaRKYCwkkFQVfcAs1fXA5V+++FGfvjJ/CxURaSxaBvGdGDhfXE28LWuT9ozCl5xw4Yq5OGazvV24mZVSoOO0yZ31j7kYvtwYK6NeADwbSxDdJEqO4k//0zOHKrUiGYXtqw/A0LFFtqoZKFjnkCAQOjgdkwgdYwHQYDVR0OBBYEFMd9jMIhF1Ylmn/Tgt9r45jk14alMIGmBgNVHSMEgZ4wgZuAFMd9jMIhF1Ylmn/Tgt9r45jk14aloXikdjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLR29vZ2xlIEluYy4xEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNVBAMTB0FuZHJvaWSCCQDC4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQBt0lLO74UwLDYKqs6Tm8/yzKkEu116FmH4rkaymUIE0P9KaMftGlMexFlaYjzmB2OxZyl6euNXEsQH8gjwyxCUKRJNexBiGcCEyj6z+a1fuHHvkiaai+KL8W1EyNmgjmyy8AW7P+LLlkR+ho5zEHatRbM/YAnqGcFh5iZBqpknHf1SKMXFh4dd239FJ1jWYfbMDMy3NS5CTMQ2XFI1MvcyUTdZPErjQfTbQe3aDQsQcafEQPD+nqActifKZ0Np0IS9L9kR/wbNvyz6ENwPiTrjV2KRkEjH78ZMcUQXg0L3BYHJ3lc69Vs5Ddf9uUGGMYldX3WfMBEmh/9iFBDAaTCK
15 |
16 |
17 |
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/java/com/app/autohighlighttts/AutoHighlightTTSComposable.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import androidx.compose.foundation.rememberScrollState
4 | import androidx.compose.foundation.text.InlineTextContent
5 | import androidx.compose.foundation.verticalScroll
6 | import androidx.compose.material3.LocalTextStyle
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.runtime.LaunchedEffect
9 | import androidx.compose.runtime.getValue
10 | import androidx.compose.runtime.mutableIntStateOf
11 | import androidx.compose.runtime.mutableStateListOf
12 | import androidx.compose.runtime.remember
13 | import androidx.compose.runtime.setValue
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.graphics.Color
16 | import androidx.compose.ui.text.TextLayoutResult
17 | import androidx.compose.ui.text.TextStyle
18 | import androidx.compose.ui.text.font.FontFamily
19 | import androidx.compose.ui.text.font.FontStyle
20 | import androidx.compose.ui.text.font.FontWeight
21 | import androidx.compose.ui.text.style.TextAlign
22 | import androidx.compose.ui.text.style.TextDecoration
23 | import androidx.compose.ui.text.style.TextOverflow
24 | import androidx.compose.ui.unit.TextUnit
25 | import com.app.autohighlighttts.composable.AutoHighlightTTSBuilder
26 | import com.app.autohighlighttts.composable.AutoHighlightTTS
27 |
28 | @Composable
29 | fun AutoHighlightTTSComposable(
30 | tts: AutoHighlightTTSEngine,
31 | autoHighlightTTSBuilder: AutoHighlightTTSBuilder,
32 | modifier: Modifier = Modifier,
33 | color: Color = Color.Unspecified,
34 | fontSize: TextUnit = TextUnit.Unspecified,
35 | fontStyle: FontStyle? = null,
36 | fontWeight: FontWeight? = null,
37 | fontFamily: FontFamily? = null,
38 | letterSpacing: TextUnit = TextUnit.Unspecified,
39 | textDecoration: TextDecoration? = null,
40 | textAlign: TextAlign? = null,
41 | lineHeight: TextUnit = TextUnit.Unspecified,
42 | overflow: TextOverflow = TextOverflow.Clip,
43 | softWrap: Boolean = true,
44 | maxLines: Int = Int.MAX_VALUE,
45 | minLines: Int = 1,
46 | inlineContent: Map = mapOf(),
47 | onTextLayout: (TextLayoutResult) -> Unit = {},
48 | style: TextStyle = LocalTextStyle.current
49 | ) {
50 | var textLineHeight by remember { mutableIntStateOf(0) }
51 | val lineOfWord = remember { mutableStateListOf() }
52 | var currentScrollingCount by remember { mutableIntStateOf(0) }
53 | val scrollable = rememberScrollState()
54 |
55 | LaunchedEffect(tts.sliderPosition) {
56 | if (tts.sliderPosition == 0f || (tts.totalWords - 2 < tts.sliderPosition)) {
57 | scrollable.animateScrollTo(0)
58 | currentScrollingCount = 0
59 | }
60 |
61 | while (lineOfWord.size > currentScrollingCount && tts.sliderPosition > lineOfWord[currentScrollingCount]) {
62 | currentScrollingCount += 1
63 | }
64 |
65 | while (lineOfWord.size > currentScrollingCount && currentScrollingCount > 0 && tts.sliderPosition <= lineOfWord[currentScrollingCount] - 1) {
66 | currentScrollingCount -= 1
67 | }
68 | scrollable.scrollTo(textLineHeight * currentScrollingCount)
69 | }
70 |
71 | AutoHighlightTTS(
72 | modifier = modifier.verticalScroll(scrollable),
73 | color = color,
74 | fontSize = fontSize,
75 | textAlign = textAlign,
76 | fontFamily = fontFamily,
77 | style = style,
78 | fontStyle = fontStyle,
79 | fontWeight = fontWeight,
80 | autoHighlightTTSBuilder = autoHighlightTTSBuilder,
81 | onTextLayout = { textLayoutResult ->
82 | if (lineOfWord.isEmpty()) {
83 | val lineCount = textLayoutResult.lineCount
84 | var lineOffset = 0
85 | var wordCount = 0
86 | for (i in 0 until lineCount) {
87 | val lineEndIndex = textLayoutResult.getLineEnd(
88 | lineIndex = i, visibleEnd = true
89 | )
90 | val lineContent =
91 | tts.mainText.substring(lineOffset, lineEndIndex)
92 | wordCount += lineContent.split(" ").count() - 1
93 | if (lineOfWord.isEmpty()) {
94 | wordCount += 1
95 | }
96 | lineOfWord.add(wordCount)
97 | lineOffset = lineEndIndex
98 | textLineHeight = (textLayoutResult.size.height / lineCount)
99 | }
100 | }
101 | onTextLayout.invoke(textLayoutResult)
102 | },
103 | letterSpacing = letterSpacing,
104 | textDecoration = textDecoration,
105 | lineHeight = lineHeight,
106 | overflow = overflow,
107 | softWrap = softWrap,
108 | maxLines = maxLines,
109 | minLines = minLines,
110 | inlineContent = inlineContent,
111 | )
112 | }
113 |
114 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # AutoHighlightTTS [](https://jitpack.io/#Mindinventory/AutoHighlightTTS)
4 | **AutoHighlightTTS** is a powerful and simple solution for integrating Text to Speech functionality into your Android app. It features automatic sentence highlighting with customizable styles, auto-scrolling text during playback, and options to set language, pitch, and speech rate. With inbuilt controls like play, pause, backward/forward by one sentence, AutoHighlightTTS ensures a seamless and interactive TTS experience for your users.
5 | ## Screenshots
6 |
7 |
8 | ### Image
9 | 
10 |
11 | ### Video
12 |
13 |
14 | https://github.com/user-attachments/assets/0069bbd0-9b1e-4e40-af84-151fd4a29147
15 |
16 |
17 |
18 | ### Key features
19 |
20 |
21 | * Android 15 support.
22 | * Simple implementation.
23 | * highlighting current sentence.
24 | * auto scroll text while text-to-speech play.
25 | * Set your custom styles for text highlighting.
26 | * Set your own language, pitch & speech Rate.
27 | * Inbuilt Functionality Support play, pause, backward and forward[one sentence], slider position, etc.
28 |
29 | # Usage
30 |
31 | #### Dependencies
32 |
33 | * Step 1. Add the JitPack repository to your project build.gradle:
34 |
35 | ```groovy
36 | allprojects {
37 | repositories {
38 | ...
39 | maven { url 'https://jitpack.io' }
40 | }
41 | }
42 | ```
43 |
44 | **or**
45 |
46 | If Android studio version is Arctic Fox then add it in your settings.gradle:
47 |
48 | ```groovy
49 | dependencyResolutionManagement {
50 | repositories {
51 | ...
52 | maven { url 'https://jitpack.io' }
53 | }
54 | }
55 | ```
56 |
57 | * Step 2. Add the dependency in your app module build.gradle:
58 |
59 | ```groovy
60 | dependencies {
61 | ...
62 | implementation 'com.github.Mindinventory:AutoHighlightTTS:X.X.X'
63 | }
64 | ```
65 |
66 | ### Implementation
67 |
68 | * Step 1. Initialization of the MiTextToSpeech inside your viewmodel :
69 |
70 | ```kotlin
71 | ...
72 |
73 | lateinit var instanceOfTTS: AutoHighlightTTSEngine
74 |
75 | init {
76 | initTTS(context)
77 | }
78 |
79 | private fun initTTS(context: Context): AutoHighlightTTSEngine {
80 | instanceOfTTS = AutoHighlightTTSEngine
81 | .getInstance()
82 | .init(context)
83 | .setLanguage(Locale.ENGLISH)
84 | .setPitchAndSpeed(1f, 1f)
85 | .setText(context.getString(R.string.text_to_speech_text))
86 | return instanceOfTTS
87 | }
88 |
89 | ...
90 | ```
91 |
92 | * Step 2. Add listeners and MITextToSpeechText inside your composable :
93 |
94 | ```kotlin
95 | ...
96 |
97 | var instanceOfTTS by remember {
98 | mutableStateOf(null)
99 | }
100 |
101 | LaunchedEffect(instanceOfTTS == null) {
102 | instanceOfTTS = viewModel.instanceOfTTS
103 | }
104 |
105 | ...
106 |
107 | // Listeners to get status
108 |
109 | tts.setOnCompletionListener {
110 | Log.e("TAG", "TTSScreen: Completed From Callback")
111 | }.setOnErrorListener {
112 | //Perform action for error
113 | }.setOnEachSentenceStartListener {
114 | Log.e("TAG", "TTSScreen: onEachSentenceStart is called")
115 | }
116 |
117 |
118 | ...
119 |
120 | // The composable function displays the text and helps us to highlight the currently spoken sentence.
121 |
122 | TTSComposable(
123 | tts = tts,
124 | textAlign = TextAlign.Center,
125 | fontFamily = fontFamily,
126 | fontWeight = FontWeight.ExtraLight,
127 | miTextHighlightBuilder = MITextHighlightBuilder(
128 | text = tts.mainText,
129 | tts.highlightTextPair.value,
130 | style = SpanStyle(
131 | fontFamily = fontFamily,
132 | color = Amaranth,
133 | fontWeight = FontWeight.Bold,
134 | )
135 | ),
136 | style = TextStyle(
137 | fontSize = 20.sp, color = Color.Black,
138 | lineHeight = 35.sp
139 | ),
140 | )
141 |
142 | ...
143 |
144 | ```
145 |
146 |
147 |
148 | ## Additional Functions
149 |
150 | | Functions | Description |
151 | |-------------------------|------------------------------------------------------------------------------------|
152 | | playTextToSpeech() | used for play TextToSpeech content |
153 | | pauseTextToSpeech() | pause the Text-to-speech if it is currently speaking |
154 | | forwardText() | Moves to the next sentence |
155 | | backwardText() | Moves to the preview sentence |
156 | | setPitchAndSpeed() | you can customize the pitch and speech as per your requirements. (float, float) |
157 |
158 | ## Guidelines
159 |
160 | #### Guideline for contributors
161 | Contribution towards our repository is always welcome, we request contributors to create a pull request to the **develop** branch only.
162 |
163 | #### Guideline to report an issue/feature request
164 | It would be great for us if the reporter can share the below things to understand the root cause of the issue.
165 |
166 | * Library version
167 | * Code snippet
168 | * Logs if applicable
169 | * Device specification like (Manufacturer, OS version, etc)
170 | * Screenshot/video with steps to reproduce the issue
171 |
172 | ### Requirements
173 |
174 | * minSdkVersion >= 24
175 | * Androidx
176 |
177 | # LICENSE!
178 |
179 | MiTextToSpeech is [MIT-licensed](/LICENSE).
180 |
181 | # Let us know!
182 | We’d be really happy if you send us links to your projects where you use our component. Just send an email to sales@mindinventory.com And do let us know if you have any questions or suggestion regarding our work.
183 |
184 |
185 |
186 |
187 |
--------------------------------------------------------------------------------
/app/src/main/java/com/app/autohighlighttts/AutoHighlightTTSScreen.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.util.Log
4 | import android.widget.Toast
5 | import androidx.annotation.DrawableRes
6 | import androidx.compose.animation.core.animateFloatAsState
7 | import androidx.compose.animation.core.tween
8 | import androidx.compose.foundation.Canvas
9 | import androidx.compose.foundation.Image
10 | import androidx.compose.foundation.background
11 | import androidx.compose.foundation.clickable
12 | import androidx.compose.foundation.layout.Arrangement
13 | import androidx.compose.foundation.layout.Box
14 | import androidx.compose.foundation.layout.Column
15 | import androidx.compose.foundation.layout.Row
16 | import androidx.compose.foundation.layout.Spacer
17 | import androidx.compose.foundation.layout.fillMaxWidth
18 | import androidx.compose.foundation.layout.height
19 | import androidx.compose.foundation.layout.padding
20 | import androidx.compose.foundation.layout.size
21 | import androidx.compose.foundation.shape.CircleShape
22 | import androidx.compose.material3.CircularProgressIndicator
23 | import androidx.compose.material3.ExperimentalMaterial3Api
24 | import androidx.compose.material3.Icon
25 | import androidx.compose.material3.IconButton
26 | import androidx.compose.material3.Slider
27 | import androidx.compose.material3.SliderDefaults
28 | import androidx.compose.material3.Text
29 | import androidx.compose.runtime.Composable
30 | import androidx.compose.runtime.DisposableEffect
31 | import androidx.compose.runtime.LaunchedEffect
32 | import androidx.compose.runtime.getValue
33 | import androidx.compose.runtime.mutableFloatStateOf
34 | import androidx.compose.runtime.mutableStateOf
35 | import androidx.compose.runtime.remember
36 | import androidx.compose.runtime.rememberCoroutineScope
37 | import androidx.compose.runtime.setValue
38 | import androidx.compose.ui.Alignment
39 | import androidx.compose.ui.Modifier
40 | import androidx.compose.ui.draw.clip
41 | import androidx.compose.ui.geometry.CornerRadius
42 | import androidx.compose.ui.geometry.Offset
43 | import androidx.compose.ui.geometry.Size
44 | import androidx.compose.ui.graphics.Color
45 | import androidx.compose.ui.platform.LocalContext
46 | import androidx.compose.ui.res.painterResource
47 | import androidx.compose.ui.res.stringResource
48 | import androidx.compose.ui.text.SpanStyle
49 | import androidx.compose.ui.text.TextStyle
50 | import androidx.compose.ui.text.font.FontWeight
51 | import androidx.compose.ui.text.style.TextAlign
52 | import androidx.compose.ui.unit.dp
53 | import androidx.compose.ui.unit.sp
54 | import androidx.hilt.navigation.compose.hiltViewModel
55 | import androidx.lifecycle.Lifecycle
56 | import androidx.lifecycle.LifecycleEventObserver
57 | import androidx.lifecycle.LifecycleOwner
58 | import androidx.lifecycle.compose.LocalLifecycleOwner
59 | import com.app.autohighlighttts.composable.AutoHighlightTTSBuilder
60 | import com.app.autohighlighttts.ui.theme.Amaranth
61 | import com.app.autohighlighttts.ui.theme.fontFamily
62 | import kotlinx.coroutines.launch
63 | import kotlin.math.roundToInt
64 | import com.app.autohighlightttssample.R
65 |
66 |
67 | @Composable
68 | fun TTSScreen(viewModel: AutoHighlightTTSViewModel = hiltViewModel()) {
69 |
70 | var instanceOfTTS by remember { mutableStateOf(null) }
71 | LaunchedEffect(instanceOfTTS == null) {
72 | instanceOfTTS = viewModel.instanceOfTTS
73 | }
74 |
75 | instanceOfTTS?.let { tts ->
76 | ComposableLifecycle { _, event ->
77 | when (event) {
78 | Lifecycle.Event.ON_PAUSE -> {
79 | tts.apply {
80 | if (autoHighlightTTS.isSpeaking) {
81 | pauseTextToSpeech()
82 | }
83 | }
84 | }
85 |
86 | else -> {}
87 | }
88 | }
89 |
90 | val context = LocalContext.current
91 | val scope = rememberCoroutineScope()
92 |
93 | tts.setOnCompletionListener {
94 | Log.e("TAG", "TTSScreen: Completed From Callback")
95 | scope.launch {
96 | Toast.makeText(context, "Completed", Toast.LENGTH_LONG).show()
97 | }
98 | }.setOnErrorListener {
99 | scope.launch {
100 | Toast.makeText(context, it, Toast.LENGTH_LONG).show()
101 | }
102 | }.setOnEachSentenceStartListener {
103 | Log.e("TAG", "TTSScreen: onEachSentenceStart is called")
104 | }
105 |
106 | Column(
107 | Modifier
108 | .fillMaxWidth()
109 | .background(Color.White)
110 | .padding(horizontal = 20.dp)
111 | ) {
112 |
113 | Text(
114 | text = stringResource(id = R.string.text_to_speech),
115 | color = Amaranth,
116 | fontWeight = FontWeight.Medium,
117 | fontSize = 30.sp,
118 | fontFamily = fontFamily,
119 | modifier = Modifier
120 | .fillMaxWidth()
121 | .padding(top = 50.dp, bottom = 20.dp),
122 | textAlign = TextAlign.Center
123 | )
124 |
125 | Box(
126 | Modifier
127 | .weight(1f)
128 | .fillMaxWidth()
129 | .padding(end = 10.dp)
130 | ) {
131 | AutoHighlightTTSComposable(
132 | tts = tts,
133 | textAlign = TextAlign.Center,
134 | fontFamily = fontFamily,
135 | fontWeight = FontWeight.ExtraLight,
136 | autoHighlightTTSBuilder = AutoHighlightTTSBuilder(
137 | text = tts.mainText,
138 | tts.highlightTextPair.value,
139 | style = SpanStyle(
140 | fontFamily = fontFamily,
141 | color = Amaranth,
142 | fontWeight = FontWeight.Bold,
143 | )
144 | ),
145 | style = TextStyle(
146 | fontSize = 20.sp, color = Color.Black,
147 | lineHeight = 35.sp
148 | ),
149 | )
150 | }
151 | Spacer(modifier = Modifier.height(20.dp))
152 | BottomStorySection(tts)
153 | }
154 | } ?: Box(contentAlignment = Alignment.Center) {
155 | CircularProgressIndicator()
156 | }
157 | }
158 |
159 | /**
160 | * This Composable Is Used For Track and Control the Progress.
161 | */
162 | @OptIn(ExperimentalMaterial3Api::class)
163 | @Composable
164 | fun BottomStorySection(instanceOfTTS: AutoHighlightTTSEngine) {
165 | var test by remember {
166 | mutableFloatStateOf(0f)
167 | }
168 | val sliderValue = animateFloatAsState(
169 | targetValue = instanceOfTTS.sliderPosition,
170 | animationSpec = tween(durationMillis = 100),
171 | label = ""
172 | )
173 |
174 | Column(
175 | modifier = Modifier.padding(vertical = 20.dp, horizontal = 10.dp),
176 | horizontalAlignment = Alignment.CenterHorizontally
177 | ) {
178 | Slider(
179 | value = sliderValue.value,
180 | onValueChange = {
181 | instanceOfTTS.sliderPosition = it
182 | test = it
183 | },
184 | valueRange = 0f..(instanceOfTTS.totalWords + 1).toFloat(),
185 | colors = SliderDefaults.colors(
186 | thumbColor = Color.Transparent, // Make the default thumb transparent
187 | activeTrackColor = Amaranth,
188 | ),
189 | onValueChangeFinished = {
190 | instanceOfTTS.sliderToUpdate((test.roundToInt()))
191 | },
192 | track = {
193 | Canvas(
194 | modifier = Modifier
195 | .fillMaxWidth()
196 | .height(24.dp) // Match slider height
197 | ) {
198 | val trackHeight = 8.dp.toPx() // Track height
199 | val activeTrackWidth =
200 | (sliderValue.value / instanceOfTTS.totalWords) * size.width
201 |
202 | // Draw inactive track (gray)
203 | drawRoundRect(
204 | color = Color.LightGray,
205 | size = Size(width = size.width, height = trackHeight),
206 | cornerRadius = CornerRadius(trackHeight / 2),
207 | topLeft = Offset(0f, (size.height - trackHeight) / 2)
208 | )
209 |
210 | // Draw active track (blue)
211 | drawRoundRect(
212 | color = Amaranth,
213 | size = Size(width = activeTrackWidth, height = trackHeight),
214 | cornerRadius = CornerRadius(trackHeight / 2),
215 | topLeft = Offset(0f, (size.height - trackHeight) / 2)
216 | )
217 | }
218 | },
219 | thumb = {
220 | // Draw the custom thumb
221 | Canvas(
222 | modifier = Modifier
223 | .size(24.dp)
224 | ) {
225 | val thumbRadius = 12.dp.toPx() // Thumb radius, proportional to slider height
226 |
227 | val thumbCenterX = (sliderValue.value * size.width).coerceIn(
228 | thumbRadius,
229 | size.width - thumbRadius
230 | ) // Constrain thumb within bounds
231 | val thumbCenterY = size.height / 2 // Thumb Y position, centered
232 |
233 | // Draw the outer transparent circle (thumb)
234 | drawCircle(
235 | color = Amaranth, // Semi-transparent white
236 | center = Offset(thumbCenterX, thumbCenterY),
237 | radius = thumbRadius
238 | )
239 | }
240 | },
241 | )
242 |
243 | StoryReadingController(instanceOfTTS)
244 | }
245 | }
246 |
247 | /**
248 | * Control the Reading Like Moving to Next , Skip or Forward.
249 | */
250 | @Composable
251 | fun StoryReadingController(instanceOfTTS: AutoHighlightTTSEngine) {
252 | Row(
253 | horizontalArrangement = Arrangement.SpaceEvenly,
254 | verticalAlignment = Alignment.CenterVertically,
255 | modifier = Modifier
256 | .fillMaxWidth()
257 | .padding(vertical = 10.dp)
258 | ) {
259 | CommonImageButton(
260 | modifier = Modifier,
261 | image = R.drawable.ic_skip_previous,
262 | enabled = (instanceOfTTS.currentCount.intValue == 0).not(),
263 | color = if ((instanceOfTTS.currentCount.intValue == 0)) Color.LightGray else Amaranth
264 | ) {
265 | instanceOfTTS.backwardText()
266 | }
267 | Box(
268 | Modifier
269 | .clip(CircleShape)
270 | .background(Amaranth)
271 | .size(64.dp)
272 | .clickable {
273 | if (instanceOfTTS.playOrPauseTTS.value) {
274 | instanceOfTTS.pauseTextToSpeech()
275 | } else {
276 | instanceOfTTS.playTextToSpeech()
277 | }
278 | }, contentAlignment = Alignment.Center
279 | ) {
280 | Image(
281 | painterResource(id = if (instanceOfTTS.playOrPauseTTS.value) R.drawable.ic_pause else R.drawable.ic_play_white),
282 | contentDescription = "",
283 | modifier = Modifier.size(24.dp)
284 | )
285 | }
286 | CommonImageButton(
287 | modifier = Modifier, image = R.drawable.ic_skip_next,
288 | enabled = (instanceOfTTS.currentCount.intValue >= instanceOfTTS.listOfStringOfParagraph.size - 1).not(),
289 | color = if ((instanceOfTTS.currentCount.intValue >= instanceOfTTS.listOfStringOfParagraph.size - 1)) Color.LightGray else Amaranth
290 | ) {
291 | instanceOfTTS.forwardText()
292 | }
293 | }
294 | }
295 |
296 |
297 | @Composable
298 | fun CommonImageButton(
299 | @DrawableRes image: Int,
300 | modifier: Modifier = Modifier,
301 | color: Color = Amaranth, enabled: Boolean = true,
302 | onClick: () -> Unit = {},
303 | ) {
304 | IconButton(
305 | enabled = enabled,
306 | onClick = { onClick() },
307 | ) {
308 | Icon(
309 | painter = painterResource(id = image),
310 | contentDescription = "",
311 | modifier = modifier.size(32.dp),
312 | tint = color
313 | )
314 | }
315 | }
316 |
317 | @Composable
318 | fun ComposableLifecycle(
319 | lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
320 | onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit
321 | ) {
322 |
323 | DisposableEffect(lifecycleOwner) {
324 | val observer = LifecycleEventObserver { source, event ->
325 | onEvent(source, event)
326 | }
327 | lifecycleOwner.lifecycle.addObserver(observer)
328 |
329 | onDispose {
330 | lifecycleOwner.lifecycle.removeObserver(observer)
331 | }
332 | }
333 | }
334 |
335 |
336 |
--------------------------------------------------------------------------------
/AutoHighlightTTS/src/main/java/com/app/autohighlighttts/AutoHighlightTTSEngine.kt:
--------------------------------------------------------------------------------
1 | package com.app.autohighlighttts
2 |
3 | import android.content.Context
4 | import android.speech.tts.TextToSpeech
5 | import android.speech.tts.UtteranceProgressListener
6 | import androidx.compose.runtime.getValue
7 | import androidx.compose.runtime.mutableFloatStateOf
8 | import androidx.compose.runtime.mutableStateOf
9 | import androidx.compose.runtime.mutableIntStateOf
10 | import androidx.compose.runtime.setValue
11 | import com.app.autohighlighttts.models.ParagraphModel
12 | import java.util.Locale
13 |
14 |
15 | class AutoHighlightTTSEngine {
16 |
17 | /**
18 | * Create Singleton Object
19 | */
20 | companion object {
21 | private var instance: AutoHighlightTTSEngine? = null
22 | fun getInstance(): AutoHighlightTTSEngine {
23 | if (instance == null) {
24 | instance = AutoHighlightTTSEngine()
25 | }
26 | return instance!!
27 | }
28 | }
29 |
30 |
31 | lateinit var autoHighlightTTS: TextToSpeech
32 | lateinit var mainText: String
33 | private lateinit var currentSpokenSentenceCopy: String
34 |
35 | var playOrPauseTTS = mutableStateOf(false)
36 | var totalWords: Int = 0
37 | var currentCount = mutableIntStateOf(0)
38 | var listOfStringOfParagraph: List = emptyList()
39 | var highlightTextPair = mutableStateOf(Pair(0, 0))
40 | var sliderPosition by mutableFloatStateOf(0f)
41 |
42 | private var stopPosition: Pair = Pair(0, 0)
43 | private var defLanguage = Locale.getDefault()
44 | private var onEachSentenceStartListener: (() -> Unit)? = null
45 | private var onDoneListener: (() -> Unit)? = null
46 | private var onErrorListener: ((String) -> Unit)? = null
47 | private var onHighlightListener: ((Pair) -> Unit)? = null
48 |
49 |
50 | /**
51 | * Initialization of [AutoHighlightTTSEngine]
52 | */
53 | fun init(app: Context): AutoHighlightTTSEngine {
54 | autoHighlightTTS = TextToSpeech(app) {
55 | if (it == TextToSpeech.SUCCESS) {
56 | autoHighlightTTS.language = defLanguage
57 | }
58 | }
59 | return this
60 | }
61 |
62 |
63 | /**
64 | * When we set the language to English in Android TTS,
65 | * it tells the system to use English pronunciation rules and phonemes to generate speech from the text you provide.
66 | */
67 | fun setLanguage(local: Locale): AutoHighlightTTSEngine {
68 | this.defLanguage = local
69 | return this
70 | }
71 |
72 |
73 | /**
74 | * [pauseTextToSpeech] pause the Text-to-speech if it is currently speaking.
75 | */
76 | fun pauseTextToSpeech(): AutoHighlightTTSEngine {
77 | if (autoHighlightTTS.isSpeaking) {
78 | autoHighlightTTS.stop()
79 | }
80 | playOrPauseTTS.value = false
81 | return this
82 | }
83 |
84 | /**
85 | * [setText] is used for the set text to MiTextToSpeech.
86 | * @param text is string text.
87 | */
88 | fun setText(text: String): AutoHighlightTTSEngine {
89 | mainText = text
90 | totalWords = countWords(mainText)
91 |
92 | // Split text into paragraphs using regex
93 | listOfStringOfParagraph = mainText.split("\\.\\s*".toRegex())
94 | // Filter out empty paragraphs
95 | .filter { it.isNotEmpty() }
96 | // Map each paragraph to a ParagraphModel
97 | .mapIndexed { _, paragraph ->
98 | // Calculate word count and range for each paragraph
99 | val startWordIndex = countWords(mainText.substring(0, mainText.indexOf(paragraph)))
100 | val endWordIndex = startWordIndex + countWords(paragraph) - 1
101 | ParagraphModel(paragraph, countWords(paragraph), startWordIndex, endWordIndex)
102 | }
103 |
104 | return this
105 | }
106 |
107 | /**
108 | * [playTextToSpeech] is used for play TextToSpeech content.
109 | */
110 | fun playTextToSpeech(): AutoHighlightTTSEngine {
111 | if (mainText.isNotBlank()) {
112 | // Adjust currentSpokenSentenceCopy if a stop position is set
113 | currentSpokenSentenceCopy = if (stopPosition.second != 0) {
114 | currentSpokenSentenceCopy.substring(stopPosition.second)
115 | } else {
116 | // Otherwise, set currentSpokenSentenceCopy to the next sentence
117 | listOfStringOfParagraph[currentCount.intValue].text
118 | }
119 |
120 | // Play the current sentence
121 | autoHighlightTTS.play(currentSpokenSentenceCopy)
122 |
123 | // Highlight the text corresponding to the current sentence
124 | highlightTextPair.value =
125 | getStartAndEndOfSubstring(
126 | mainText,
127 | listOfStringOfParagraph[currentCount.intValue].text
128 | )
129 |
130 | playOrPauseTTS.value = true
131 |
132 | // Set the UtteranceProgressListener for handling TTS events
133 | autoHighlightTTS.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
134 | override fun onStart(utteranceId: String?) {
135 | onEachSentenceStartListener?.invoke()
136 | }
137 |
138 | override fun onDone(utteranceId: String?) {
139 | stopPosition = Pair(0, 0)
140 |
141 | // If there are more sentences to speak
142 | if (currentCount.intValue < listOfStringOfParagraph.size - 1) {
143 | // Move to the next sentence
144 | currentSpokenSentenceCopy =
145 | listOfStringOfParagraph[++currentCount.intValue].text
146 | // Speak the next sentence
147 | autoHighlightTTS.speak(
148 | currentSpokenSentenceCopy,
149 | TextToSpeech.QUEUE_FLUSH,
150 | null, TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED
151 | )
152 | // Highlight the text corresponding to the next sentence
153 | highlightTextPair.value = getStartAndEndOfSubstring(
154 | mainText,
155 | currentSpokenSentenceCopy
156 | )
157 | // Update the progress
158 | updateProgress(currentCount.intValue)
159 | } else {
160 | // Reset values when all content is spoken
161 | playOrPauseTTS.value = false
162 | currentCount.intValue = 0
163 | sliderPosition = 0f
164 | highlightTextPair.value = Pair(0, 0)
165 |
166 | // Call onDoneListener when the entire content is spoken
167 | onDoneListener?.invoke()
168 | }
169 | }
170 |
171 | // Handle TTS errors
172 | @Deprecated("Deprecated in Java")
173 | override fun onError(utteranceId: String?) {
174 | onErrorListener?.invoke(utteranceId ?: "")
175 | }
176 |
177 | // Handle range start events (highlighting)
178 | override fun onRangeStart(
179 | utteranceId: String?,
180 | start: Int,
181 | end: Int,
182 | frame: Int
183 | ) {
184 | super.onRangeStart(utteranceId, start, end, frame)
185 | // Update the stop position
186 | stopPosition = Pair(start, end)
187 | // Increment the slider position
188 | if (sliderPosition < totalWords) {
189 | sliderPosition += 1f
190 | }
191 | // Invoke the onHighlightListener
192 | onHighlightListener?.invoke(Pair(start, end))
193 | }
194 | })
195 | } else {
196 | onErrorListener?.invoke("Text to speech text is empty")
197 | }
198 | return this
199 | }
200 |
201 |
202 | /**
203 | * Updates the slider progress based on the current index.
204 | */
205 | private fun updateProgress(currentIndex: Int = currentCount.intValue): AutoHighlightTTSEngine {
206 | sliderPosition = listOfStringOfParagraph[currentIndex].startIndex.toFloat()
207 | return this
208 | }
209 |
210 | /**
211 | * [sliderToUpdate] is responsible for calculating and update the value when user changes the slider.
212 | * @param currentIndex slider current position
213 | */
214 | fun sliderToUpdate(currentIndex: Int): AutoHighlightTTSEngine {
215 | //below condition is work when the over current slider word count is grater then total word count.
216 | if (currentIndex >= totalWords) {
217 | currentCount.intValue = 0
218 | sliderPosition = listOfStringOfParagraph[currentCount.intValue].startIndex.toFloat()
219 | highlightFunction()
220 | pauseTextToSpeech()
221 | return this
222 | }
223 |
224 | /**
225 | * paragraph we are finding the [ParagraphModel] base on currentIndex
226 | */
227 | val paragraph: ParagraphModel =
228 | listOfStringOfParagraph.firstOrNull { it.startIndex < currentIndex && it.endIndex >= currentIndex }
229 | ?: return this // No paragraph found for current index
230 |
231 | currentCount.intValue = listOfStringOfParagraph.indexOf(paragraph)
232 |
233 |
234 | /**
235 | * On Sliding we are calculating percentage and based on that whether that word is in between or not,
236 | * If it's in between then we are skipping that word.
237 | */
238 | val percentage =
239 | calculatePercentage(paragraph.startIndex, paragraph.endIndex, currentIndex) / 100
240 | val splitIndex = (paragraph.text.length * percentage).toInt()
241 | var adjustedSplitIndex = splitIndex
242 | if (paragraph.text.length > splitIndex) {
243 | if (paragraph.text[splitIndex] != ' ' || paragraph.text[splitIndex - 1] != ' ') {
244 | while (true) {
245 | if (paragraph.text[++adjustedSplitIndex] != ' ') break
246 | }
247 | }
248 | }
249 | stopPosition = Pair(0, adjustedSplitIndex)
250 | currentSpokenSentenceCopy = paragraph.text
251 |
252 | sliderPosition = currentIndex.toFloat()
253 |
254 | highlightFunction()
255 | pauseTextToSpeech()
256 |
257 | return this
258 | }
259 |
260 | /**
261 | * [forwardText] Moves to the next sentence.
262 | */
263 | fun forwardText(): AutoHighlightTTSEngine {
264 | // Check if there is a next sentence
265 | if (currentCount.intValue < listOfStringOfParagraph.size - 1) {
266 | // Reset stopPosition
267 | stopPosition = Pair(0, 0)
268 |
269 | // Move to the next sentence and update currentSpokenSentenceCopy
270 | currentSpokenSentenceCopy = listOfStringOfParagraph[++currentCount.intValue].text
271 |
272 | // Apply highlighting
273 | highlightFunction()
274 |
275 | // If TTS is enabled, stop current playback and play the next sentence
276 | if (playOrPauseTTS.value) {
277 | pauseTextToSpeech()
278 | autoHighlightTTS.play(currentSpokenSentenceCopy)
279 | playOrPauseTTS.value = true
280 | }
281 |
282 | // Update progress
283 | updateProgress()
284 | }
285 | return this
286 | }
287 |
288 |
289 | /**
290 | * [backwardText] using this function we go one sentence back
291 | */
292 | fun backwardText(): AutoHighlightTTSEngine {
293 | if (currentCount.intValue <= 0) {
294 | return this
295 | }
296 |
297 | stopPosition = Pair(0, 0)
298 | currentCount.intValue--
299 | val currentSentence = listOfStringOfParagraph[currentCount.intValue].text
300 |
301 | if (playOrPauseTTS.value) {
302 | pauseTextToSpeech()
303 | autoHighlightTTS.play(currentSentence)
304 | playOrPauseTTS.value = true
305 | }
306 |
307 | highlightFunction()
308 | updateProgress()
309 |
310 | return this
311 | }
312 |
313 | /**
314 | * [highlightFunction] is responsible for Highlight the text which are speaking.
315 | */
316 | private fun highlightFunction(): AutoHighlightTTSEngine {
317 | highlightTextPair.value =
318 | getStartAndEndOfSubstring(mainText, listOfStringOfParagraph[currentCount.intValue].text)
319 | return this
320 | }
321 |
322 | /**
323 | * [setOnCompletionListener] is trigger when speech is successfully complete.
324 | */
325 | fun setOnCompletionListener(onDoneListener: () -> Unit): AutoHighlightTTSEngine {
326 | this.onDoneListener = onDoneListener
327 | return this
328 | }
329 |
330 | /**
331 | * [setOnErrorListener] is used for getting error of Text-to-speech.
332 | */
333 | fun setOnErrorListener(onErrorListener: (String) -> Unit): AutoHighlightTTSEngine {
334 | this.onErrorListener = onErrorListener
335 | return this
336 | }
337 |
338 | /**
339 | * [setOnEachSentenceStartListener] is used for getting each sentence start callback
340 | */
341 | fun setOnEachSentenceStartListener(onEachSentenceStartListener: () -> Unit): AutoHighlightTTSEngine {
342 | this.onEachSentenceStartListener = onEachSentenceStartListener
343 | return this
344 | }
345 |
346 |
347 | /**
348 | * @param pitch Speech pitch. 1.0 is the normal pitch, lower values lower the tone of
349 | * the synthesized voice, greater values increase it.
350 | * @param speed Speech rate. 1.0 is the normal speech rate, lower values slow down
351 | * the speech (0.5 is half the normal speech rate), greater values accelerate it (2.0 is
352 | * twice the normal speech rate).
353 | */
354 | fun setPitchAndSpeed(pitch: Float = 1f, speed: Float = 1f): AutoHighlightTTSEngine {
355 | autoHighlightTTS.setPitch(pitch)
356 | autoHighlightTTS.setSpeechRate(speed)
357 | return this
358 | }
359 | }
--------------------------------------------------------------------------------