La reconnaissance de la parole Android et le texte à la parole sont facilitées.
implementation ' net.gotev:speech:x.y.z ' Remplacez xyz par
Pour commencer à utiliser la bibliothèque, vous devez l'initialiser dans votre activité
public class YourActivity extends Activity {
Override
protected void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . your_layout );
Speech . init ( this , getPackageName ());
}
@ Override
protected void onDestroy () {
// prevent memory leaks when activity is destroyed
Speech . getInstance (). shutdown ();
}
} Vous pouvez trouver une application de démonstration entièrement fonctionnelle qui utilise cette bibliothèque dans le répertoire examples . Il suffit de vérifier le projet et d'essayer.
À l'intérieur d'une activité:
try {
// you must have android.permission.RECORD_AUDIO granted at this point
Speech . getInstance (). startListening ( new SpeechDelegate () {
@ Override
public void onStartOfSpeech () {
Log . i ( "speech" , "speech recognition is now active" );
}
@ Override
public void onSpeechRmsChanged ( float value ) {
Log . d ( "speech" , "rms is now: " + value );
}
@ Override
public void onSpeechPartialResults ( List < String > results ) {
StringBuilder str = new StringBuilder ();
for ( String res : results ) {
str . append ( res ). append ( " " );
}
Log . i ( "speech" , "partial result: " + str . toString (). trim ());
}
@ Override
public void onSpeechResult ( String result ) {
Log . i ( "speech" , "result: " + result );
}
});
} catch ( SpeechRecognitionNotAvailable exc ) {
Log . e ( "speech" , "Speech recognition is not available on this device!" );
// You can prompt the user if he wants to install Google App to have
// speech recognition, and then you can simply call:
//
// SpeechUtil.redirectUserToGoogleAppOnPlayStore(this);
//
// to redirect the user to the Google App page on Play Store
} catch ( GoogleVoiceTypingDisabledException exc ) {
Log . e ( "speech" , "Google voice typing must be enabled!" );
} Dans onDestroy de votre activité, ajoutez:
@ Override
protected void onDestroy () {
Speech . getInstance (). shutdown ();
}Pour éviter les fuites de mémoire.
Ajoutez ceci à votre mise en page:
< LinearLayout
android : orientation = " vertical "
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @+id/linearLayout " >
< net .gotev.speech.ui.SpeechProgressView
android : id = " @+id/progress "
android : layout_width = " 120dp "
android : layout_height = " 150dp " />
</ LinearLayout > Il est important que la SpeechProgressView soit toujours à l'intérieur d'un linearlayout pour fonctionner correctement. Vous pouvez ajuster la largeur et la hauteur en conséquence aux paramètres de hauteur de la barre (voir ci-dessous).
Ensuite, lorsque vous commencez la reconnaissance de la parole, passez également le SpeechProgressView :
Speech . getInstance (). startListening ( speechProgressView , speechDelegate );Vous pouvez définir les 5 couleurs des 5 barres comme vous le souhaitez. Ce n'est qu'un exemple:
int [] colors = {
ContextCompat . getColor ( this , android . R . color . black ),
ContextCompat . getColor ( this , android . R . color . darker_gray ),
ContextCompat . getColor ( this , android . R . color . black ),
ContextCompat . getColor ( this , android . R . color . holo_orange_dark ),
ContextCompat . getColor ( this , android . R . color . holo_red_dark )
};
speechProgressView . setColors ( colors ); int [] heights = { 60 , 76 , 58 , 80 , 55 };
speechProgressView . setBarMaxHeightsInDp ( heights );À l'intérieur d'une activité:
Speech . getInstance (). say ( "say something" );Vous pouvez également fournir un rappel pour recevoir le statut:
Speech . getInstance (). say ( "say something" , new TextToSpeechCallback () {
@ Override
public void onStart () {
Log . i ( "speech" , "speech started" );
}
@ Override
public void onCompleted () {
Log . i ( "speech" , "speech completed" );
}
@ Override
public void onError () {
Log . i ( "speech" , "speech error" );
}
});Vous pouvez configurer divers paramètres en utilisant les méthodes de setter sur l'instance de la parole, que vous pouvez obtenir comme celle-ci n'importe où dans votre code:
Speech . getInstance ()Reportez-vous à Javadocs pour une référence complète.
Par défaut, la journalisation de la bibliothèque est désactivée. Vous pouvez activer le journal de débogage en invoquant:
Logger . setLogLevel ( LogLevel . DEBUG );Où que vous vouliez dans votre code. Vous pouvez ajuster le niveau de détail du débogage à OFF.
Le journal de bibliothèque utilise android.util.Log par défaut, vous obtiendrez donc la sortie dans LogCat . Si vous souhaitez rediriger les journaux vers différentes sorties ou utiliser un autre enregistreur, vous pouvez fournir votre propre implémentation de délégué comme ceci:
Logger . setLoggerDelegate ( new Logger . LoggerDelegate () {
@ Override
public void error ( String tag , String message ) {
//your own implementation here
}
@ Override
public void error ( String tag , String message , Throwable exception ) {
//your own implementation here
}
@ Override
public void debug ( String tag , String message ) {
//your own implementation here
}
@ Override
public void info ( String tag , String message ) {
//your own implementation here
}
}); Utilisez Speech.getInstance().getSpeechToTextLanguage() et Speech.getinstance().getTextToSpeechVoice() . Vérifiez l'application de démonstration pour un exemple complet.
Utilisez Speech.getInstance().getSupportedSpeechToTextLanguages(listener) et Speech.getInstance().getSupportedTextToSpeechVoices() . Vérifiez l'application de démonstration pour un exemple complet.
Utilisez Speech.getInstance().setLocale(locale) et Speech.getInstance().setVoice(voice) . Vérifiez l'application de démonstration pour un exemple complet.
Lorsque vous définissez les paramètres régionaux, la voix est automatiquement changée par la voix par défaut de cette langue. Si vous souhaitez définir une voix particulière, n'oubliez pas de la réinitialiser à chaque fois que vous changez également le lieu.
Merci à @zagum pour la mise en œuvre originale de la vue de reconnaissance vocale.
Copyright (C) 2019 Aleksandar Gotev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Merci à Kristiyan Petrov pour l'examen du code, les corrections de bogues et les idées d'amélioration des bibliothèques.