Dans ce Tuto je vais faire parler mon Android Phone avec une liste aléatoire de phrases et de mots grâce à la synthèse vocale.
Je crée mon fichier de ma fenêtre avec juste un bouton pour lancer mon action.
Dans ma classe j'implémente l'objet TextToSpeech, qui permet de lancer la synthèse vocale
public class CommandeVocal extends Activity implements TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechDemo";
//creation de objet TextToSpeech
private TextToSpeech mTts;
private Button mAgainButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_xml);
//instanciation de l'objet mTts
mTts = new TextToSpeech(this,this );
// The button is disabled in the layout.
// It will be enabled upon initialization of the TTS engine.
mAgainButton = (Button) findViewById(R.id.again_button);
mAgainButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParleandroidPhone ();
}
});
}
Je crée mon tableau de phrases aléatoire
private static final Random RANDOM = new Random();
private static final String[] HELLOS = {
"Bonjour",
"Comment tu vas",
"Perpignan ",
"J'aime Android France"
};
Une methode importante dans notre classe c'est la méthode onInit qui permet de configurer la langue de notre synthèse vocale.
// Implements TextToSpeech.OnInitListener.
public void onInit(int status) {
// vérification de la disponibilité de la synthèse vocale.
if (status == TextToSpeech.SUCCESS) {
//le choix de la langue ici français
int result = mTts.setLanguage(Locale.FRANCE);
// vérification ici si cette langue est supporté par le terminal et si elle existe
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
//renvoi une erreur sur la console logcat.
Log.e(TAG, "Language is not available.");
} else {
mAgainButton.setEnabled(true);
ParleandroidPhone ();
}
} else {
// si la synthèse vocal n'est pas disponible
Log.e(TAG, "Could not initialize TextToSpeech.");
}
Puis ma Methode ParleandroidPhone qui lance aléatoirement une phrase
private void ParleandroidPhone () {
// choix aléatoire de la phrase.
int helloLength = HELLOS.length;
String hello = HELLOS[RANDOM.nextInt(helloLength)];
mTts.speak(hello, TextToSpeech.QUEUE_FLUSH, null);
}












