2011-01-11 11 views
10

Estoy tratando de obtener la API de Android TTS para leer mi "enunciado" y luego llamar al oyente onUtteranceCompleted() sin éxito. He registrado mi objeto TTS y devuelve ÉXITO, por lo que no puedo entender por qué mi devolución de llamada no se llama.Android TTS onUtteranceLa devolución de llamada completa no se llama

He intentado buscar ayuda, pero parece que otros tienen dificultades con esto también. ¿Me estoy perdiendo algo simple?

Gracias por cualquier ayuda que pueda ofrecer.

package com.test.mytts; 

import java.util.HashMap; 

import android.app.Activity; 
import android.media.AudioManager; 
import android.os.Bundle; 
import android.speech.tts.TextToSpeech; 
import android.speech.tts.TextToSpeech.OnInitListener; 
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener 
{ 
    TextView tv; 
    private TextToSpeech _tts; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     tv = new TextView(this); 

     tv.setText("MyTTS: "); 

     super.onCreate(savedInstanceState); 
     setContentView(tv); 

     _tts = new TextToSpeech(this, this); 
    } 

    @Override 
    public void onInit(int status) 
    { 
     HashMap<String, String> myHashAlarm = new HashMap<String, String>(); 

     myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION)); 
     myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test"); 

     if (status == TextToSpeech.SUCCESS) 
     { 
      Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show(); 

      int result = _tts.setOnUtteranceCompletedListener(this); 

      tv.append(String.valueOf(result)); 

      _tts.setSpeechRate((float) .5); 

      _tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm); 
     } 
     else 
      Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onUtteranceCompleted(String utteranceId) 
    { 
     Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onDestroy() 
    { 
     super.onDestroy(); 
     _tts.shutdown(); 
    } 
} 
+0

No veo nada malo con lo que tiene, pero probablemente sea mejor usar las declaraciones de registro que las tostadas para rastrear qué está sucediendo. Luego puede revisar el pedido en logcat. –

+0

creo que esto le ayudará a: [http://stackoverflow.com/questions/4658376/how-to-know-when-tts-is-finished][1] [1]: http: //stackoverflow.com/questions/4658376/how-to-know-when-tts-is-finished – uriellabs

Respuesta

17

Creo que a menos que especifique una expresión con un id, como: método de completado

map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceid); 

su habla no será llamado.

en este caso, el mapa es el Hashmap que pasa al motor cuando habla.

+0

Tiene el mismo problema que el mencionado anteriormente. Y tengo esta clave agregada al mapa y la paso hablar. raro ... –

+0

generalmente especifico el oyente todas las veces que llamo hablar. Podría ayudar. – ekawas

+0

de alguna manera lo tengo trabajando ahora. pero no tengo idea de por qué está funcionando ahora. algo era un poco raro, supongo. –

18

Llamar al setOnUtteranceCompletedListener dentro de la función onInit del objeto tts.

Si desea realizar cambios en la IU en la llamada de la función onUtteranceCompleted, agregue el código dentro de un método runOnUIThread.

Y recuerde agregar el valor Hashmap parámetro al llamar al hablar de función()

Ejemplo:

TextToSpeech tts= new TextToSpeech(context, new OnInitListener() { 

@Override 
public void onInit(int status) { 

    mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() { 

     @Override 
     public void onUtteranceCompleted(String utteranceId) { 

      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
       //UI changes 
       } 
      }); 
     } 
    }); 

} 
}); 


HashMap<String, String> params = new HashMap<String, String>(); 

params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId"); 

tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params); 
2

esto funcionará para usted en el nivel API> = 15

import java.util.HashMap; 
import java.util.Locale; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.speech.tts.TextToSpeech; 
import android.speech.tts.TextToSpeech.OnInitListener; 
import android.speech.tts.UtteranceProgressListener; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class MainActivity extends Activity implements OnInitListener{ 

    private static final int CHECK_TTS_DATA = 0X123; 
    protected static final String TAG = MainActivity.class.getSimpleName(); 
    private TextToSpeech textToSpeech; 
    private Button buttonSayIt; 
    private EditText editTextTts; 
    String tts; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     buttonSayIt=(Button) findViewById(R.id.buttonSayIt); 
     editTextTts=(EditText) findViewById(R.id.editTextTts); 
     buttonSayIt.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       tts=editTextTts.getText().toString(); 
       Log.d(TAG, tts); 
       speach(tts,"you_utterance_id"); 
      } 
     }); 
     //check for TTs data 
     Intent checkTtsDataIntent=new Intent(); 
     checkTtsDataIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); 
     startActivityForResult(checkTtsDataIntent, CHECK_TTS_DATA); 

    } 

    protected void speach(String tts,String utteranceId) { 
     HashMap<String, String> params = new HashMap<String, String>(); 
     params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,utteranceId); 
     textToSpeech.speak(tts,TextToSpeech.QUEUE_FLUSH,params); 
    } 

    @Override 
    public void onInit(int status) { 
     if(status==TextToSpeech.SUCCESS){ 
      if(textToSpeech.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE){ 
       textToSpeech.setLanguage(Locale.US); 
      } 
     }else if(status==TextToSpeech.ERROR){ 
      Toast.makeText(this, "Sorry Text To Speach faild", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if(requestCode==CHECK_TTS_DATA){ 
      if(resultCode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){ 
       textToSpeech=new TextToSpeech(this, this);  
       textToSpeech.setOnUtteranceProgressListener(utteranceProgressListener); 
      }else{ 
       Intent installTtsIntent=new Intent(); 
       installTtsIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); 
       startActivity(installTtsIntent); 
      } 
     } 
    } 

    UtteranceProgressListener utteranceProgressListener=new UtteranceProgressListener() { 

     @Override 
     public void onStart(String utteranceId) { 
      Log.d(TAG, "onStart (utteranceId :"+utteranceId+") "); 
     } 

     @Override 
     public void onError(String utteranceId) { 
      Log.d(TAG, "onError (utteranceId :"+utteranceId+") "); 
     } 

     @Override 
     public void onDone(String utteranceId) { 
      Log.d(TAG, "onDone (utteranceId :"+utteranceId+") "); 
     } 
    }; 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 
Cuestiones relacionadas