我已經在線教程實現了一個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