Android Google文本到语音作为一个sperate类,可以在需要时调用?
我一直在尝试使用GoogleTTS引擎编写一个语音输出类。 但在整个互联网上,我只在MainActivity的Android Google文本到语音作为一个sperate类,可以在需要时调用?,android,text-to-speech,Android,Text To Speech,我一直在尝试使用GoogleTTS引擎编写一个语音输出类。 但在整个互联网上,我只在MainActivity的onCreate和其他重写方法中找到布局和使用TTS服务的示例 我想创建一个类,它有一个类似speakThis(String someText)的方法,可以说出传递的字符串。您需要的是一个服务,下面是我使用的一个: import android.app.Service; import android.content.Intent; import android.o
onCreate
和其他重写方法中找到布局和使用TTS服务的示例
我想创建一个类,它有一个类似speakThis(String someText)的方法,可以说出传递的字符串。您需要的是一个服务,下面是我使用的一个:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.Locale;
/**
* TextToSpeech Service
*
* Este servicio nos permite hacer uso del motor de TTS desde un servicio, es decir, invocándolo
* desde cualquier lugar.
* Antes de poder hacer uso del motor, el mismo debe estar inicializado (se tiene que haber llamado
* al metodo onInit, lo cual sucede automaticamente cuando se completa el proceso de inicializacion)
*
* Cada vez que se quiera usar, se debe iniciar este servicio con un intento, el cual debe traer
* como EXTRA el texto que se quiere reproducir.
*/
public class TTS_Service extends Service implements TextToSpeech.OnInitListener{
private static final String TAG = "TTS_Service";
public static final String EXTRA_TTS_TEXT = "com.package.EXTRA_TTS_TEXT";
private String textToSpeak;
private static boolean initDone;
private TextToSpeech tts;
/* ON CREATE */
/* ********* */
@Override
public void onCreate() {
super.onCreate();
initDone = false;
tts = new TextToSpeech(this,this/*OnInitListener*/);
}
/* ON INIT */
/* ******* */
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
initDone = true;
Log.i(TAG, "TTS inicializado correctamente");
speakOut();
} else {
tts = null;
initDone = false;
Log.e(TAG, "Fallo al inicializar TTS");
}
}
/* ON START COMAMND */
/* **************** */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
textToSpeak = ""; // Asumimos que no va a haber un texto
// Acoording to documentation, intent may be null if service is restarted
// so first we need to check if it is null before asking for extras
if ((null != intent) && (intent.hasExtra(EXTRA_TTS_TEXT))){
textToSpeak = intent.getStringExtra(EXTRA_TTS_TEXT);
}
// Si ya se inicializo y hay un texto para reproducir, hazlo!
if (initDone) {
speakOut();
}
// Debe ser stoppeado explicitamente
return START_STICKY;
}
/* ON DESTROY */
/* ********** */
@Override
public void onDestroy() {
// Shutdown TTS before destroying the Service
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
/* ON BIND */
/* ******* */
@Override
public IBinder onBind(Intent arg0) {
return null;
}
/* SPEAK OUT */
/* ********* */
private void speakOut() {
// First need to check if textToSpeak is not null
if ((null != textToSpeak) && (!textToSpeak.equals(""))) {
if (null != tts) {
tts.setSpeechRate((float) 0.85); // Set speech rate a bit slower than normal
tts.setLanguage(Locale.getDefault()); // Set deafualt Locale as Speech Languaje
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null, null); // Don't need and utteranceID to track
//} else {
tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null);
//}
} else {
Log.e(TAG, "No se puede hablar porque no existe TTS");
}
}else{
Log.w(TAG, "No hay texto para reproducir. Si se trata de la primer inicializacion, no pasa nada");
}
}
}
当你想调用它时,你只需:
Intent tts_intent = new Intent(getApplicationContext(), com.package.TTS_Service.class);
tts_intent.putExtra(TTS_Service.EXTRA_TTS_TEXT, texto_you_want);
startService(tts_intent);
希望有帮助 您需要的是服务,以下是我使用的服务:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.Locale;
/**
* TextToSpeech Service
*
* Este servicio nos permite hacer uso del motor de TTS desde un servicio, es decir, invocándolo
* desde cualquier lugar.
* Antes de poder hacer uso del motor, el mismo debe estar inicializado (se tiene que haber llamado
* al metodo onInit, lo cual sucede automaticamente cuando se completa el proceso de inicializacion)
*
* Cada vez que se quiera usar, se debe iniciar este servicio con un intento, el cual debe traer
* como EXTRA el texto que se quiere reproducir.
*/
public class TTS_Service extends Service implements TextToSpeech.OnInitListener{
private static final String TAG = "TTS_Service";
public static final String EXTRA_TTS_TEXT = "com.package.EXTRA_TTS_TEXT";
private String textToSpeak;
private static boolean initDone;
private TextToSpeech tts;
/* ON CREATE */
/* ********* */
@Override
public void onCreate() {
super.onCreate();
initDone = false;
tts = new TextToSpeech(this,this/*OnInitListener*/);
}
/* ON INIT */
/* ******* */
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
initDone = true;
Log.i(TAG, "TTS inicializado correctamente");
speakOut();
} else {
tts = null;
initDone = false;
Log.e(TAG, "Fallo al inicializar TTS");
}
}
/* ON START COMAMND */
/* **************** */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
textToSpeak = ""; // Asumimos que no va a haber un texto
// Acoording to documentation, intent may be null if service is restarted
// so first we need to check if it is null before asking for extras
if ((null != intent) && (intent.hasExtra(EXTRA_TTS_TEXT))){
textToSpeak = intent.getStringExtra(EXTRA_TTS_TEXT);
}
// Si ya se inicializo y hay un texto para reproducir, hazlo!
if (initDone) {
speakOut();
}
// Debe ser stoppeado explicitamente
return START_STICKY;
}
/* ON DESTROY */
/* ********** */
@Override
public void onDestroy() {
// Shutdown TTS before destroying the Service
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
/* ON BIND */
/* ******* */
@Override
public IBinder onBind(Intent arg0) {
return null;
}
/* SPEAK OUT */
/* ********* */
private void speakOut() {
// First need to check if textToSpeak is not null
if ((null != textToSpeak) && (!textToSpeak.equals(""))) {
if (null != tts) {
tts.setSpeechRate((float) 0.85); // Set speech rate a bit slower than normal
tts.setLanguage(Locale.getDefault()); // Set deafualt Locale as Speech Languaje
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null, null); // Don't need and utteranceID to track
//} else {
tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null);
//}
} else {
Log.e(TAG, "No se puede hablar porque no existe TTS");
}
}else{
Log.w(TAG, "No hay texto para reproducir. Si se trata de la primer inicializacion, no pasa nada");
}
}
}
当你想调用它时,你只需:
Intent tts_intent = new Intent(getApplicationContext(), com.package.TTS_Service.class);
tts_intent.putExtra(TTS_Service.EXTRA_TTS_TEXT, texto_you_want);
startService(tts_intent);
希望有帮助 “我想创建一个类,它有一个像speakThis(String someText)这样的方法,可以说出传递的字符串。”。。。这就是TextToSpeech类已经具备的功能。这已经是一项服务了。不管示例如何,只需转到TextToSpeech文档即可。“我想创建一个类,它有一个类似speakThis(String someText)的方法,可以说出传递的字符串。”。。。这就是TextToSpeech类已经具备的功能。这已经是一项服务了。不管这些示例如何,只需转到TextToSpeech文档即可。