Reconocimiento de voz de Android y texto a discurso fácil.
implementation ' net.gotev:speech:x.y.z ' Reemplazar xyz con
Para comenzar a usar la biblioteca, debe inicializarla en su actividad
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 ();
}
} Puede encontrar una aplicación de demostración completamente en funcionamiento que use esta biblioteca en el directorio examples . Simplemente consulte el proyecto y pruébelo.
Dentro de una actividad:
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!" );
} En onDestroy de su actividad, agregue:
@ Override
protected void onDestroy () {
Speech . getInstance (). shutdown ();
}Para evitar fugas de memoria.
Agregue esto a su diseño:
< 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 > Es importante que SpeechProgressView siempre esté dentro de un LinearLayout para funcionar correctamente. Puede ajustar el ancho y la altura en consecuencia a la configuración de la altura de la barra (ver más abajo).
Luego, cuando comience el reconocimiento de voz, pase también el SpeechProgressView :
Speech . getInstance (). startListening ( speechProgressView , speechDelegate );Puede configurar todos los 5 colores de baras como desee. Este es solo un ejemplo:
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 );Dentro de una actividad:
Speech . getInstance (). say ( "say something" );También puede proporcionar una devolución de llamada para recibir el estado:
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" );
}
});Puede configurar varios parámetros utilizando los métodos Setter en la instancia de discurso, que puede obtener así en cualquier lugar de su código:
Speech . getInstance ()Consulte Javadocs para obtener una referencia completa.
Por defecto, el registro de la biblioteca está deshabilitado. Puede habilitar el registro de depuración invocando:
Logger . setLogLevel ( LogLevel . DEBUG );donde quiera en su código. Puede ajustar el nivel de detalle de la depuración a OFF.
El registrador de la biblioteca usa android.util.Log de forma predeterminada, por lo que obtendrá la salida en LogCat . Si desea redirigir los registros a una salida diferente o usar un registrador diferente, puede proporcionar su propia implementación de delegado como esta:
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
}
}); Use Speech.GetInstance Speech.getinstance().getTextToSpeechVoice() Speech.getInstance().getSpeechToTextLanguage() Consulte la aplicación de demostración para obtener un ejemplo completo.
Use Speech.getInstance().getSupportedSpeechToTextLanguages(listener) Speech.getInstance().getSupportedTextToSpeechVoices() Consulte la aplicación de demostración para obtener un ejemplo completo.
Use Speech.getInstance().setLocale(locale) y Speech.getInstance().setVoice(voice) . Consulte la aplicación de demostración para obtener un ejemplo completo.
Cuando establece el localidad, la voz se cambia automáticamente a la voz predeterminada de ese idioma. Si desea establecer una voz en particular, recuerde volver a establecerla cada vez que cambie el local.
Gracias a @zagum por la implementación original de la vista de reconocimiento de voz.
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.
Gracias a Kristiyan Petrov por su revisión de código, correcciones de errores e ideas de mejora de la biblioteca.