在Android中,使用TextToSpeech類設(shè)置文本的性別,您需要首先創(chuàng)建一個(gè)TextToSpeech實(shí)例,然后使用setGender()方法設(shè)置性別。以下是一個(gè)簡(jiǎn)單的示例:
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity implements OnInitListener {
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 創(chuàng)建TextToSpeech實(shí)例
tts = new TextToSpeech(this, this);
// 設(shè)置語言為中文
int result = tts.setLanguage(TextToSpeech.LANG_CHINESE);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
// 設(shè)置性別為女性
tts.setGender(TextToSpeech.GENDER_FEMALE);
speakText("你好,我是一個(gè)女性助手。");
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.i("TTS", "Initialization successful");
} else {
Log.e("TTS", "Initialization failed");
}
}
private void speakText(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)TextToSpeech實(shí)例,并設(shè)置了語言為中文。然后,我們使用setGender()方法將性別設(shè)置為女性。最后,我們調(diào)用speakText()方法讓文本說話。您可以根據(jù)需要更改性別為男性(TextToSpeech.GENDER_MALE)或其他類型。