2015-12-09 61 views
0
I'm doing a POC on text to speech. 

有一個條件,即當過設備在收件箱中獲得新的SMS文本語音應該告訴用戶「您已收到新的消息」。但文本語音不適用於加載或收聽。如何文本廣播接收器添加到語音

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

對於要調用的方法onInit(),你必須初始化的TextToSpeech對象,如下圖所示:

t1 = new TextToSpeech(this, this);