Text To Speech - Speak the text
TextToSpeech library facilitate us to convert text in to voice in a variety of languages. It have an initListener, we must initialize the parameters of speaking like language setting etc. It have a variety of options like
AndroidManifest.xml
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codeexpo.texttospeechsample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
|
MainActivity.java
|
public class MainActivity extends AppCompatActivity {
EditText message;
Button speakNow;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message=findViewById(R.id.message);
speakNow=findViewById(R.id.speak_now);
///////Initialize Listener of TextToSpeech////////////
textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK); //Set Language
textToSpeech.setPitch((float) 0.5); //Set Pitch
textToSpeech.setSpeechRate((float) 1.5); //Set Speech rate
}
}
});
/////////////////////////////////////////////////////
speakNow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//message.getText().toString() is the text to speak
//TextToSpeech.QUEUE_FLUSH Use to flush the text after speak
//TextToSpeech.QUEUE_ADD Use to append text in prevuous and speak
textToSpeech.speak(message.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}
|
activity_main.xml
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:hint="Enter Message to Speak" />
<Button
android:id="@+id/speak_now"
android:background="@color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:text="Speak Now" />
</LinearLayout>
|
Comments
Post a Comment