简体   繁体   English

简单的TextToSpeech代码

[英]Simple TextToSpeech code

I want to make a simple TextToSpeech code. 我想制作一个简单的TextToSpeech代码。 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(). 如果允许线程进入睡眠状态,则在睡眠后调用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. 如果是这样,那么在此时查看您的代码,该tts似乎没有初始化,并且为null,因此将崩溃并出现异常。

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. 该代码应防止出现异常,但是如果TTS引擎的初始化花费的时间太长,那么您将不会说“正在加载”。 Also, I am guessing the 5 second (which is a really long time btw) sleep is to allow for it to get initialized? 另外,我猜测5秒钟的睡眠(实际上是很长的时间)是为了让它初始化?

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. 与错误输出一样,您必须按照建议使用有效参数初始化TextToSpeech对象,并提供ContextOnInitListener对象。

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; 包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 { 公共类MainActivity扩展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);
    }
}

} }

speak is deprecated 不推荐使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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