jeudi 31 mai 2012

Faite parler votre Android


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.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/again_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="teste" />
</LinearLayout>
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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_xml);
//instanciation de l'objet  mTts
mTts = new TextToSpeech(this,this );
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",
"Bienveunue dans notre page truc et astuce informatique",
};
Une méthode 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);
}


Share:

0 commentaires:

Enregistrer un commentaire

Contributeurs

Membres

free counters