I'm doing a POC on text to speech.
有一种情况是,当设备在收件箱中收到新短信时,文本语音应该告诉用户“您收到了一条新邮件”。但是,文本到语音不能正在加载或收听。
public class SMSReceiver extends BroadcastReceiver implements TextToSpeech.OnInitListener
{
TextToSpeech t1;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
speakOut();
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
t1.speak("You have one new message would you like to read it", TextToSpeech.QUEUE_FLUSH, null);
}
}
这是我的短信接收方法。 在这里,我可以正确地发送和接收短信,但在阅读消息后,文字演讲无效,任何人都可以为我提供解决方案。
答案 0 :(得分:0)
检查您的日志。首先,t1为空,所以你将获得NPE,另一件事是你不应该在广播接收器中执行繁重的任务,而是从那里开始调用IntentService。还记得调用构造函数。详细信息: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#TextToSpeech(android.content.Context,android.speech.tts.TextToSpeech.OnInitListener)
答案 1 :(得分:0)
对于要调用的onInit()
方法,您必须初始化TextToSpeech
的对象,如下所示:
t1 = new TextToSpeech(this, this);