2011-06-11 14 views
113

¿Es esto posible sin modificar las API de Android? He encontrado un artículo sobre esto. Hay un comentario que debería hacer modificaciones a las API de Android. Pero no dice cómo hacer la modificación. ¿Alguien puede darme algunas sugerencias sobre cómo hacer eso? Gracias!¿Cómo puedo usar el reconocimiento de voz sin el molesto diálogo en teléfonos Android


He encontrado este artículo; SpeechRecognizer Sus necesidades son casi las mismas que las mías. ¡Es una buena referencia para mí!


Tengo totalmente solucionado este problema.
Busqué en Google un código de ejemplo utilizable from this China website Aquí está mi código fuente

package voice.recognition.test; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.speech.RecognitionListener; 
import android.speech.RecognizerIntent; 
import android.speech.SpeechRecognizer; 
import android.widget.Button; 
import android.widget.TextView; 
import java.util.ArrayList; 
import android.util.Log; 



public class voiceRecognitionTest extends Activity implements OnClickListener 
{ 

    private TextView mText; 
    private SpeechRecognizer sr; 
    private static final String TAG = "MyStt3Activity"; 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      Button speakButton = (Button) findViewById(R.id.btn_speak);  
      mText = (TextView) findViewById(R.id.textView1);  
      speakButton.setOnClickListener(this); 
      sr = SpeechRecognizer.createSpeechRecognizer(this);  
      sr.setRecognitionListener(new listener());   
    } 

    class listener implements RecognitionListener   
    { 
      public void onReadyForSpeech(Bundle params) 
      { 
        Log.d(TAG, "onReadyForSpeech"); 
      } 
      public void onBeginningOfSpeech() 
      { 
        Log.d(TAG, "onBeginningOfSpeech"); 
      } 
      public void onRmsChanged(float rmsdB) 
      { 
        Log.d(TAG, "onRmsChanged"); 
      } 
      public void onBufferReceived(byte[] buffer) 
      { 
        Log.d(TAG, "onBufferReceived"); 
      } 
      public void onEndOfSpeech() 
      { 
        Log.d(TAG, "onEndofSpeech"); 
      } 
      public void onError(int error) 
      { 
        Log.d(TAG, "error " + error); 
        mText.setText("error " + error); 
      } 
      public void onResults(Bundle results)     
      { 
        String str = new String(); 
        Log.d(TAG, "onResults " + results); 
        ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); 
        for (int i = 0; i < data.size(); i++) 
        { 
           Log.d(TAG, "result " + data.get(i)); 
           str += data.get(i); 
        } 
        mText.setText("results: "+String.valueOf(data.size()));   
      } 
      public void onPartialResults(Bundle partialResults) 
      { 
        Log.d(TAG, "onPartialResults"); 
      } 
      public void onEvent(int eventType, Bundle params) 
      { 
        Log.d(TAG, "onEvent " + eventType); 
      } 
    } 
    public void onClick(View v) { 
      if (v.getId() == R.id.btn_speak) 
      { 
       Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);   
       intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
       intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); 

       intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); 
        sr.startListening(intent); 
        Log.i("111111","11111111"); 
      } 
    } 
} 

Asegúrese de eliminar los registros de los molestos después de la depuración!

+1

Es definitivamente posible hacerlo, como he visto otras aplicaciones lo hacen (Voz infinito) pero en cuanto a cómo, no tengo ni idea.Me imagino que podrías comenzar por descargar la fuente de Android y verificar en la API donde está la voz, y luego experimentar extendiendo ... – Eric

+1

según lo observado por Femi, asegúrate de tener '' en su archivo AndroidManifest.xml; de lo contrario, SpeechRecognizer no recuperará ningún audio – nommer

Respuesta

63

Utilice la interfaz SpeechRecognizer. Su aplicación necesita tener el permiso RECORD_AUDIO, y luego puede crear un SpeechRecognizer, darle un RecognitionListener y luego llamar a su método startListening. Recibirá retrollamadas para el oyente cuando el reconocedor de voz esté listo para comenzar a escuchar el habla y cuando reciba el habla y lo convierta en texto.

+0

Gracias por su asesoramiento. Voy a intentar ahora – Jim31837

+9

Además, no olvides destruir SpeechRecognier en el método OnDestroy() como se indica aquí: http://stackoverflow.com/a/19931355/2048266 para no obtener 'se ha filtrado ServiceConnection android.speech.SpeechRecognizer $ Connection @ 414f0e40 que originalmente estaba enlazado aquí' error – nommer

+0

¿Puede mostrarme un ejemplo? Además, ¿puedo usar esto mientras la pantalla está apagada? –

6

GAST tiene una práctica clase abstracta que puede usar para usar la clase SpeechRecognizer con muy poco código nuevo. También hay un ejemplo de ejecutar el SpeechRecognizer como un servicio en segundo plano usando this y this

+0

¿Te importaría guiarme sobre cómo implementarlos en MainActivity? ¿Qué significa esto "* Use {@link Intent} s para iniciar y detenerlo?" Muchas gracias – Dante

+0

¿Puedes mostrarme un ejemplo? Además, ¿puedo usar esto mientras la pantalla está apagada? –

4

¡Gracias por publicar esto! He encontrado que es útil para definir el oyente onclick en alcrear:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mText = (TextView) findViewById(R.id.textView1);  
    MyRecognitionListener listener = new MyRecognitionListener(); 
    sr = SpeechRecognizer.createSpeechRecognizer(this);  
    sr.setRecognitionListener(listener); 

    findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) 
     { 
       Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
       intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US"); 
       intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1); 
       intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); 
       sr.startListening(intent); 
     } 
    });  
} 
3

me tienen intentado para almacenar toda mi aprendizaje de TTS y STT en this Github Repo. Si te gusta uno, entonces puedes usar mi proyecto.

Se utilizó el patrón de fábrica para convertir la voz en texto en la línea de diálogo sin molestar

SpeechToText (STT).

TranslatorFactory.getInstance().getTranslator(TranslatorFactory.TRANSLATOR_TYPE.SPEECH_TO_TEXT, HomeActivity.this) 
            .initialize("Hello There", HomeActivity.this); 

salida: -

enter image description here

TextToSpeech (TTS)

TranslatorFactory.getInstance().getTranslator(TranslatorFactory.TRANSLATOR_TYPE.TEXT_TO_SPEECH, HomeActivity.this) 
               .initialize((null != message && !message ? message : "Invalid Input"), HomeActivity.this); 

salida: -

enter image description here

Cuestiones relacionadas