如何整合文本到语音功能?
以下是我的代码: -
public class TtsActivity extends Activity implements OnInitListener {
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.main);
inputText = (EditText) findViewById(R.id.input_text);
speakButton = (Button) findViewById(R.id.speak_button);
speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text != null && text.length() > 0) {
Toast.makeText(TtsActivity.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);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
System.out.println("Code is:- " + requestCode);
System.out.println("Code is:- " + resultCode);
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
System.out.println("Code is:- " + resultCode);
// success, create the TTS instance
tts = new TextToSpeech(this, this);
} else {
System.out.println("Code is:- " + resultCode);
// missing data, install it
Intent installIntent = new Intent();
installIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(TtsActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG)
.show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(TtsActivity.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
}
如果我运行上面的代码,谷歌Android市场是开放的,如果我安装应用程序然后文本到语音是完成工作,但如果我没有安装应用程序错误发生。
所以,请帮助我。
答案 0 :(得分:3)
这是因为Text To Speech在您的设备上需要TTS引擎。如果您的设备上没有安装TTS引擎,它会将您重定向到市场并允许您下载相同的内容。所以在您安装该引擎后,您的应用会找到TTS引擎并在您的设备上正常工作。
如需更多参考,请访问:
编辑:
TextToSpeech mTts;
mTts = new TextToSpeech(this,
this // TextToSpeech.OnInitListener
);
...
mTts.setPitch(2.3); //change it as per your need
...
mTts.speak(s,TextToSpeech.QUEUE_FLUSH,null);