📅  最后修改于: 2020-10-10 01:34:45             🧑  作者: Mango
在android中,您可以借助TextToSpeech类将文本转换为语音。转换完成后,您可以播放或创建声音文件。
TextToSpeech类的常用方法如下:
Method | Description |
---|---|
int speak (String text, int queueMode, HashMap |
converts the text into speech. Queue Mode may be QUEUE_ADD or QUEUE_FLUSH. Request parameters can be null, KEY_PARAM_STREAM, KEY_PARAM_VALUME etc. |
int setSpeechRate(float speed) | it sets the speed for the speech. |
int setPitch(float speed) | it sets the pitch for the speech. |
int setLanguage (Locale loc) | it sets the locale specific language for the speech. |
void shutdown() | it releases the resource set by TextToSpeech Engine. |
int stop() | it interrupts the current utterance (whether played or rendered to file) and discards other utterances in the queue. |
您需要实现TextToSpeech.OnInitListener接口,以便在TextToSpeech引擎上执行事件处理。
此界面中只有一种方法。
Method | Description |
---|---|
void onInit (int status) | Called to signal the completion of the TextToSpeech engine initialization. The status can be SUCCESS or ERROR. |
让我们编写代码将文本转换为语音。
拖动一个textview,一个edittext和一个用于布局的按钮。现在,activity_main.xml文件将如下所示:
让我们看看说出给定文本的代码。
package com.example.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button buttonSpeak;
private EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
buttonSpeak = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.editText1);
buttonSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
speakOut();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
buttonSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = editText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
您需要在真实设备(例如移动设备)上运行它以测试应用程序。
Next:带有速度和音高选项的TextToSpeech示例