这是我的 tts 服务代码:
public class SMSTTSService extends Service implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener {
private TextToSpeech tts;
private String spokenText;
@Override
public void onCreate() {
tts = new TextToSpeech(this, this);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
speakOut(spokenText);
}
/*if (result != TextToSpeech.LANG_MISSING_DATA && result != TextToSpeech.LANG_NOT_SUPPORTED) {
tts.speak(c, TextToSpeech.QUEUE_FLUSH, null);
}*/
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public void onUtteranceCompleted(String uttId) {
stopSelf();
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
spokenText = intent.getStringExtra("spoken_txt");
}
}
并且从接收器我打电话给服务,比如
public class Receiver extends BroadcastReceiver {
private static final String TAG = "SMSReceiver";
@Override
public void onReceive(Context context, Intent intent) {
for(int i=0; i<msgs.length; i++) {
....
Intent intentTTS = new Intent(context, SMSTTSService.class);
intentTTS.putExtra("spoken_txt", msgBody);
context.startService(intentTTS);
}
但是即使我有循环,服务也只会执行一次。如何让我在循环中不止一次有声音?我做错了什么?