I have a text to speech function in my android app that works to an onClick event, there is an issue when the activity starts, the text to speech starts without clicking the button, is there a line of code I can put in to stop this happening, thank you.
package com.androidhive.texttospeech;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button button1;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
button1 = (Button) findViewById(R.id.button1);
txtText = (TextView) findViewById(R.id.txtText);
// button on click event
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
The reason why this happens is because you invoke speakOut# In the onInit() method, remove speakOut():
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
// speakOut();
}
I saw these codes in onInit(), which will be called after the TextToSpeech is instantiated and initialized successfully. See the speakOut() here? That's what causes your problem.
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
Related
There are some errors that I can't solve after copying the source code. Can anyone know what should I do?
Here are the errors:
Cannot resolve method 'sendMessage' in 'Handler'
Class 'Anonymous class derived from Handler' must either be declared abstract or implement abstract method 'publish(LogRecord)' in 'Handler'
MusicPlayer.java
package com.example.serenityapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.logging.Handler;
public class MusicPlayer extends AppCompatActivity {
ImageView play, prev, next, imageView;
TextView songTitle;
SeekBar mSeekBarTime, mSeekBarVol;
static MediaPlayer mMediaPlayer;
private Runnable runnable;
private AudioManager mAudioManager;
int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
// initializing views
play = findViewById(R.id.play);
prev = findViewById(R.id.prev);
next = findViewById(R.id.next);
songTitle = findViewById(R.id.songTitle);
imageView = findViewById(R.id.imageView);
mSeekBarTime = findViewById(R.id.seekBarTime);
mSeekBarVol = findViewById(R.id.seekBarVol);
// creating an ArrayList to store our songs
final ArrayList<Integer> songs = new ArrayList<>();
songs.add(0, R.raw.sound1);
songs.add(1, R.raw.sound2);
songs.add(2, R.raw.sound3);
songs.add(3, R.raw.sound4);
songs.add(4, R.raw.sound5);
// intializing mediaplayer
mMediaPlayer = MediaPlayer.create(getApplicationContext(), songs.get(currentIndex));
// seekbar volume
int maxV = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curV = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSeekBarVol.setMax(maxV);
mSeekBarVol.setProgress(curV);
mSeekBarVol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//above seekbar volume
//
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSeekBarTime.setMax(mMediaPlayer.getDuration());
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
play.setImageResource(R.drawable.ic_playbtn_foreground);
} else {
mMediaPlayer.start();
play.setImageResource(R.drawable.ic_pausebtn_foreground);
}
songNames();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMediaPlayer != null) {
play.setImageResource(R.drawable.ic_pausebtn_foreground);
}
if (currentIndex < songs.size() - 1) {
currentIndex++;
} else {
currentIndex = 0;
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer = MediaPlayer.create(getApplicationContext(), songs.get(currentIndex));
mMediaPlayer.start();
songNames();
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMediaPlayer != null) {
play.setImageResource(R.drawable.ic_pausebtn_foreground);
}
if (currentIndex > 0) {
currentIndex--;
} else {
currentIndex = songs.size() - 1;
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer = MediaPlayer.create(getApplicationContext(), songs.get(currentIndex));
mMediaPlayer.start();
songNames();
}
});
}
private void songNames() {
if (currentIndex == 0) {
songTitle.setText("Sound 1");
imageView.setImageResource(R.drawable.gridbg3);
}
if (currentIndex == 1) {
songTitle.setText("Sound 2");
imageView.setImageResource(R.drawable.gridbg3);
}
if (currentIndex == 2) {
songTitle.setText("Sound 3");
imageView.setImageResource(R.drawable.gridbg3);
}
if (currentIndex == 3) {
songTitle.setText("Sound 4");
imageView.setImageResource(R.drawable.gridbg3);
}
if (currentIndex == 4) {
songTitle.setText("Sound 5");
imageView.setImageResource(R.drawable.gridbg3);
}
// seekbar duration
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mSeekBarTime.setMax(mMediaPlayer.getDuration());
mMediaPlayer.start();
}
});
mSeekBarTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mMediaPlayer.seekTo(progress);
mSeekBarTime.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (mMediaPlayer != null) {
try {
if (mMediaPlayer.isPlaying()) {
Message message = new Message();
message.what = mMediaPlayer.getCurrentPosition();
handler.sendMessage(message); //**ERROR IN THIS PART**
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
//**ERROR IN THIS PART**
#SuppressLint("Handler Leak") Handler handler = new Handler () {
public void handleMessage (Message msg) {
mSeekBarTime.setProgress(msg.what);
}
};
}
You have imported the wrong package. The Handler that you were expecting is present in android.os.Handler. But you have imported java.util.logging.Handler.
Importing the correct package will resolve both the errors.
Inside MusicPlayer.java , make the following changes:
package com.example.serenityapplication;
import androidx.appcompat.app.AppCompatActivity;
...
import android.os.Handler;
I want to make an application which can speak a different language, the text of which which will be written in a text field, which may be English, Bengali or any other language. I use this code but can not speak in different language. It is always speaking in English or which language I set in Google-Text-speech from phone setting.
Here is my java code
package com.example.texttospeech;
import android.util.Log;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
TextToSpeech tts;
EditText input;
TextView TextCount;
Button b1, b2;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.editText);
TextCount = (TextView) findViewById(R.id.TextCount);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
tts = new TextToSpeech(this, this);
TextCountNow();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String text = input.getText().toString();
if (text.isEmpty()) {
String EmptyText = "Nothing found in text fild. please Write something to read.";
tts.speak(EmptyText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(MainActivity.this, "Text is empty", Toast.LENGTH_LONG).show();
} else if (text.length() > 5000) {
String FaildText = "Text Ought of length. Maximum length is 5000. Please remove some text and try again";
tts.speak(FaildText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), "Ought of length. Maximum length is 5000.", Toast.LENGTH_LONG).show();
} else {
String ReadingText = text + ". Text reading completed";
tts.speak(ReadingText, TextToSpeech.QUEUE_FLUSH, null);
}
break;
case R.id.button1:
input.setText("");
break;
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
#SuppressWarnings("deprecation")
Locale bahasa = tts.getLanguage();
int result = tts.setLanguage(bahasa);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "This Language is not supported", Toast.LENGTH_SHORT).show();
Log.e("TTS", "This Language is not supported");
} else {
//do nathing
}
} else {
Log.e("TTS", "initialization faild");
}
}
public void TextCountNow(){
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
int textLanth = input.getText().length();
TextCount.setText("" + textLanth);
h.postDelayed(this, 500);
}
};
h.postDelayed(r, 500);
}
}
For Bengali Language :
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int result = textToSpeechService.setLanguage(new Locale("bn"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED
) {
Toast.makeText(mContext, "Speech Service Not Ready", Toast.LENGTH_SHORT).show();
} else {
textToSpeechService.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
stopBanglaReading();
}
#Override
public void onError(String utteranceId) {
}
});
int voicePitch = settings.getInt("ExplVoicePitch", 10);
int voiceSpeed = settings.getInt("ExplVoiceSpeed", 8);
textToSpeechService.setSpeechRate((float) voiceSpeed / 10);
textToSpeechService.setPitch((float) voicePitch / 10);
startSpeaking(onubad);
}
} else {
Toast.makeText(mContext, "Speech Service Not Ready, Please Try Again....", Toast.LENGTH_LONG).show();
}
}
});
Issue : speak failed:not bound to tts engine
I am implementing textToSpeech functionality. I am getting the exception as speak failed: not bound to tts engine. I am implementing the async task with it. the async task will be reading the mail. And i want to convert the mail body to speech.
package com.example.trynot;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Locale;
import com.example.trynot.MainActivity.ReadMailSample;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Notify extends Activity implements TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
public Notify()
{
System.out.println("Inside Constructor");
speakOut();
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
System.out.println("inside INIT");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
System.out.println("inside SPeak out");
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
}
}
You should move instatiation of tts engine instance to onCreate, this line:
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
change to:
public TextToSpeech tts;
and add inside your onCreate:
tts = new TextToSpeech(MainActivity.c, Notify.this);
And - whats most important - do not use constructor in Activity derived classes:
public Notify()
{
System.out.println("Inside Constructor");
speakOut();
}
should be your onCreate:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//speakOut(); // here tts is not yet initialized, call it in onInit on success
//tts = new TextToSpeech(MainActivity.c, Notify.this); // whats MainActivity.c?
tts = new TextToSpeech(this, this);
}
your google text to speech engine may be disable... once check it on your setting
if it is disable it also shows the same error
I am really new to Android Programming. I am working on a simple app: FlashLight for Android.
I need the app to continue run in background if the user presses the menubutton or locks the screen. The light should not stop until the user presses the button the stop the light.
Below is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity
extends Activity {
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if(camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch(RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if(isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage() {
if(isFlashOn) {
btnSwitch.setImageResource(R.drawable.btn_switch_on);
} else {
btnSwitch.setImageResource(R.drawable.btn_switch_off);
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound() {
if(isFlashOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash) {
turnOnFlash();
}
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if(camera != null) {
camera.release();
camera = null;
}
}
}
You;re turning off the light in onPause. When the screen is locked or the app is minimized, onPause is called. If you don't want that to happen, don't call it there.
I think you are searching for Services: http://developer.android.com/guide/components/services.html
They are very similar to an Activity but do dot provide a user interface and can run in the background.
I'm trying to implement Text to Speech onto my app. I've followed the following guide but my app keeps crashing after the splash screen.
link: http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/
Main Activity Class I have this
String alertMessage = AppResources.ALERT_MSG;
SpeakDemo speak = new SpeakDemo(null, alertMessage);
speak.speakOut();
If I remove the speak.speakOut(); line the app works fine.
App Resources is another class with the following message box
public static String ALERT_MSG = "Welcome!";
The SpeakDemo Class is:
import java.util.Locale;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class SpeakDemo implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private Context context;
private String message;
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut(){
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
Any Ideas?
Thanks
You need to instantiate the TextToSpeech.
Change
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
tts = new TextToSpeech(context, this);
}
//FOR TEXT TO SPEECH
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
String msg=text.getText().toString();
if(status==TextToSpeech.SUCCESS)
{
tts.setLanguage(Locale.US);
tts.speak(msg,TextToSpeech.QUEUE_FLUSH,null);
}
else
Log.e("TTS","INITILIZATION FAILED");
}
public void onDestroy()
{
if (tts!=null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
Xml:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:onClick="TTS"/>
Mainactivity:
TextToSpeech textToSpeech;
textToSpeech=new TextToSpeech(TTSpeech.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS)
{
result=textToSpeech.setLanguage(Locale.ENGLISH);
}
else
{
Toast.makeText(TTSpeech.this, "speech not work", Toast.LENGTH_SHORT).show();
}
}
});
}
public void TTS(View view) {
switch (view.getId())
{
case R.id.button:
if(result== TextToSpeech.LANG_NOT_SUPPORTED || result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(TTSpeech.this, "speech not nt work", Toast.LENGTH_SHORT).show();
}
else
{
text=ed.getText().toString();
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
break;
}
if you get problem you can comment me.