简单的TextToSpeech代码

时间:2015-04-01 11:24:22

标签: java android

我想制作一个简单的TextToSpeech代码。我的代码在这里:

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

但是我收到了这个错误:

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)

我错过了什么?我需要在代码中添加什么内容?

5 个答案:

答案 0 :(得分:1)

如果您允许线程进入睡眠状态,则在睡眠后调用tts.speak()。如果是这样,那么在查看你的代码时,tts似乎没有被初始化并且为null因此会因异常而崩溃。

此代码应该可以防止异常,但是如果TTS引擎的初始化时间太长,那么您就不会说它是加载。此外,我猜测5秒(这是一个非常长的时间顺便说一句)睡眠是允许它初始化?

   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);
}

}

答案 1 :(得分:0)

将活动实施为;

  public class AndroidTextToSpeech extends Activity implements TextToSpeech.OnInitListener {

答案 2 :(得分:0)

在错误输出中,您必须按照建议使用有效参数初始化TextToSpeech对象,提供ContextOnInitListener个对象。

这是一个示例init(希望它有帮助):

TextToSpeech tts = new TextToSpeech(getApplicationContext(), 
  new TextToSpeech.OnInitListener() {
      @Override
      public void onInit(int status) {
             if(status != TextToSpeech.ERROR){
                 tts.setLanguage(Locale.US);
             }              
      }
  });

答案 3 :(得分:0)

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);
    }
}

}

尝试上面的代码

答案 4 :(得分:0)

此处是我的代码:

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实现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);
    }
}

}

发言已被弃用