简体   繁体   中英

Simple TextToSpeech code

I want to make a simple TextToSpeech code. My code is here:

TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("This is a Alert Application", TextToSpeech.QUEUE_ADD,null,null);

But I am getting this error:

Error:(100, 28) error: no suitable constructor found for TextToSpeech(MainActivity,MainActivity)
constructor TextToSpeech.TextToSpeech(Context,OnInitListener,String) is not applicable
(actual and formal argument lists differ in length)
constructor TextToSpeech.TextToSpeech(Context,OnInitListener) is not applicable
(actual argument MainActivity cannot be converted to OnInitListener by method invocation conversion)

What am I missing? What i need to put in the code?

If you allow of your thread to sleep and after sleep are you calling tts.speak(). if so, at that point looking at your code, the tts does not seem to be initialized and is null so will crash with an exception.

This code should prevent the exception, but if the initialization of the TTS engine takes too long, then you won't get it to say Loading. Also, I am guessing the 5 second (which is a really long time btw) sleep is to allow for it to get initialized?

code

   public class mainj extends Activity implements OnInitListener {

   private TextToSpeech myTTS;
   // status check code
   private int MY_DATA_CHECK_CODE = 0;

   @Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.loadscreen);
   Intent checkTTSIntent = new Intent();
   checkTTSIntent
     .setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
   startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
   Thread logoTimer = new Thread() {
    public void run() {
        try {
            try {
                sleep(5000);
                speakWords("loading");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //waiting for the sleep
            splash_wait()

        }

        finally {
            finish();
        }
      }

    };
     logoTimer.start();
   }

  // speak the user text
  private void speakWords(String speech) {

     // speak straight away
     if(myTTS != null)
     {
    myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
     }
    }

    // act on result of TTS data check
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MY_DATA_CHECK_CODE) {
       if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
        // the user has the necessary data - create the TTS
        myTTS = new TextToSpeech(this, this);
    } else {
        // no data - install it now
        Intent installTTSIntent = new Intent();
        installTTSIntent
                .setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        startActivity(installTTSIntent);
       }
   }
}

 // setup TTS
 public void onInit(int initStatus) {

 // check for successful instantiation
 if (initStatus == TextToSpeech.SUCCESS) {
    if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
        myTTS.setLanguage(Locale.US);
  } else if (initStatus == TextToSpeech.ERROR) {
    Toast.makeText(this, "Sorry! Text To Speech failed...",
            Toast.LENGTH_LONG).show();
   }

    private void splash_wait() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            Intent i = new Intent(SplashActivity.this, LoginActivity.class);
            startActivity(i);
            finish();
        }
    }, SPLASH_TIME_OUT);
}

}

将活动实施为;

  public class AndroidTextToSpeech extends Activity implements TextToSpeech.OnInitListener {

As in error output you have to initialize TextToSpeech object with valid parameter, as suggested, providing a Context and an OnInitListener objects.

This is a sample init (hope it helps):

TextToSpeech tts = new TextToSpeech(getApplicationContext(), 
  new TextToSpeech.OnInitListener() {
      @Override
      public void onInit(int status) {
             if(status != TextToSpeech.ERROR){
                 tts.setLanguage(Locale.US);
             }              
      }
  });
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{private int result = 0;
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tts = new TextToSpeech(this, this);
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    txtText = (EditText) findViewById(R.id.txtText);
    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        {
            speakOut();
        }
    });
}

// shutdown tts when activity destroy
@Override
public void onDestroy()
{
    // Don't forget to shutdown!
    if (tts != null)
    {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

// It will called before TTS started
@Override
public void onInit(int status)
{
    // TODO Auto-generated method stub
    // check status for TTS is initialized or not
    if (status == TextToSpeech.SUCCESS)
    {
        // if TTS initialized than set language
        result = tts.setLanguage(Locale.US);

        // tts.setPitch(5); // you can set pitch level
        // tts.setSpeechRate(); //you can set speech speed rate

        // check language is supported or not
        // check language data is available or not
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
        {
            Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
            // disable button
            btnSpeak.setEnabled(false);
        }
        else
        {
            // if all is good than enable button convert text to speech
            btnSpeak.setEnabled(true);
        }
    }
    else
    {
        Log.e("TTS", "Initilization Failed");
    }
}

// call this method to speak text
private void speakOut()
{
    String text = txtText.getText().toString();
    if (result != tts.setLanguage(Locale.US))
    {
        Toast.makeText(getApplicationContext(), "Enter right Words...... ", Toast.LENGTH_LONG).show();
    }
    else
    {
        // speak given text
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

}

try above code

Here is my code at the moment:

package com.example.texttospeech;

    import java.util.Locale;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.SharedPreferences.Editor;
    import android.speech.tts.TextToSpeech;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

public class MainActivity extends Activity implements TextToSpeech.OnInitListener {

private int result = 0;
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tts = new TextToSpeech(this, this);
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    txtText = (EditText) findViewById(R.id.txtText);
    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            speakOut();
        }
    });
}

// shutdown tts when activity destroy
@Override
public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

// It will called before TTS started
@Override
public void onInit(int status) {
    // TODO Auto-generated method stub
    // check status for TTS is initialized or not
    if (status == TextToSpeech.SUCCESS) {
        // if TTS initialized than set language
        result = tts.setLanguage(Locale.US);

        // tts.setPitch(5); // you can set pitch level
        // tts.setSpeechRate(); //you can set speech speed rate

        // check language is supported or not
        // check language data is available or not
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
            // disable button
            btnSpeak.setEnabled(false);
        } else {
            // if all is good than enable button convert text to speech
            btnSpeak.setEnabled(true);
        }
    } else {
        Log.e("TTS", "Initilization Failed");
    }
}

// call this method to speak text
private void speakOut() {
    String text = txtText.getText().toString();
    if (result != tts.setLanguage(Locale.US)) {
        Toast.makeText(getApplicationContext(), "Enter right Words...... ", Toast.LENGTH_LONG).show();
    } else {
        // speak given text
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

}

speak is deprecated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM