我已经在线教程实现了一个android TTS代码。所有的教程都有一个文本框和一个提交按钮来捕捉它想说的文本。我的目标是从文件中获取文本,然后讲话,并且不需要用户输入(因为此模块将作为课程实施,并且所有用户输入将在主要活动中进行)。Android TTS - 应用程序意外停止
,我已经实现的代码是
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyTextToSpeech extends Activity implements OnInitListener{
/** Called when the activity is first created. */
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//inputText = (EditText) findViewById(R.id.input_text);
// speakButton = (Button) findViewById(R.id.speak_button);
// speakButton.setOnClickListener(new OnClickListener() {
//public void onClick(View v) {
// String text = inputText.getText().toString();
// if (text!=null && text.length()>0) {
// Toast.makeText(MyTextToSpeech.this, "Saying: " + text, Toast.LENGTH_LONG).show();
//tts.speak(text, TextToSpeech.QUEUE_ADD, null);
//
//}
// }
//});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
tts.speak("hi this is a test", TextToSpeech.QUEUE_ADD, null); //Added by me
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(MyTextToSpeech.this, "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(MyTextToSpeech.this, "Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
在上面的代码我已注释其中文本正在从用户捕获的线。当'tts.speak'方法在onClick方法中时,代码完美运行。当我最终得到它的代码是行为不当,并给出'空指针异常',并关闭我的应用程序。
如何解决上述问题。
感谢提前一吨。 PS:如果我之前通过使用命令tts = new TextToSpeech(this,this)启动TTS,在主要活动中,空指针异常不存在,但应用程序不会说话。
非常感谢您的解释。它现在正在运作。我将tts.speak放在onInit()方法中。 – user1576339 2012-08-09 18:33:12
一个问题)我上面的代码中的哪个语句调用'onInit()'方法?这对我将来会有所帮助,所以我不会做出类似的错误。 – user1576339 2012-08-11 11:50:47
当你像这样创建'TextToSpeech'对象时:'tts = new TextToSpeech(this,this);'。这启动了“TextToSpeech”对象的初始化。当初始化完成并且'TextToSpeech'对象准备好接受请求时,它会调用你的'onInit()'方法。 – 2012-08-12 22:16:20