Android 语音播报实现

来源:互联网 发布:vb.net timer控件 编辑:程序博客网 时间:2024/05/17 21:42

    文章主要讲的是以前做项目时实现的来短信或来电话时语音播报的功能实现,记录下来做个总结,其中有些数据库的值是自己在其他地方加的开关。

    1.实现语音播报的关键 -- 语音播报工具类(TtsUtil.java

    

    

package com.android.mms.transaction;import android.content.Context;import android.provider.Settings;import android.speech.tts.TextToSpeech;import android.speech.tts.UtteranceProgressListener;import android.speech.tts.TextToSpeech.OnInitListener;import android.util.Log;public class TtsUtil {public static TextToSpeech mTts;public static void read(Context ctx, final String content) {Log.d("dwj","messageRead = "+ Settings.Secure.getInt(ctx.getContentResolver(),"hands_free_mode", 0));if (Settings.Secure.getInt(ctx.getContentResolver(), "hands_free_mode",0) == 0) {return;}if (null != mTts) {mTts.stop();try {mTts.shutdown();} catch (Exception e) {e.printStackTrace();}}mTts = new TextToSpeech(ctx, new OnInitListener() {@Overridepublic void onInit(int status) {if (status == TextToSpeech.SUCCESS) {if (null != mTts) {mTts.setSpeechRate(1.0f);mTts.speak(content, TextToSpeech.QUEUE_FLUSH, null);mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {@Overridepublic void onDone(String utteranceId) {mTts.stop();mTts.shutdown();}@Overridepublic void onError(String utteranceId) {mTts.stop();mTts.shutdown();}@Overridepublic void onStart(String utteranceId) {}});} else {Log.e("RFLauncher", "Cann't create TextToSpeech object");}}}});}}

    

    2.1 短信接收时播报

    SmsReceiverService.java中的handleSmsReceived()函数中添加即可:


    

StringBuffer SMSAddress = new StringBuffer();            StringBuffer SMSContent = new StringBuffer();            Bundle bundle = intent.getExtras();            if(bundle != null){            Object[] pdusObjects = (Object[])bundle.get("pdus");            SmsMessage[] messages = new SmsMessage[pdusObjects.length];            for(int i=0; i<pdusObjects.length; i++){            messages[i] = SmsMessage.createFromPdu((byte[])pdusObjects[i]);            }            for(SmsMessage message : messages){            SMSAddress.append(message.getDisplayOriginatingAddress()); // send number            //SMSContent.append(message.getDisplayMessageBody()); // send content            }            }            String senderName = getContactNameFromPhoneNum(getApplicationContext()                                                      ,SMSAddress.toString());            if(Settings.Secure.getInt(getContentResolver(), "hands_free_message", 0) == 1){            if(senderName.equals("")){                TtsUtil.read(getApplicationContext(), getResources().getString(R.string.new_message_from)+ SMSAddress.toString());                }else{                if(IsNum(senderName)){                String speekName = senderName.replaceAll(".{1}(?!$)", "$0 ");                TtsUtil.read(getApplicationContext(), getResources().getString(R.string.new_message_from) + speekName);                } else {                TtsUtil.read(getApplicationContext(), getResources().getString(R.string.new_message_from) + senderName);                }                }            }

    

    2.2 短信对话框弹出时播报

    DialogModeActivity.java中的setDialogView()函数中添加即可:


   

if(Settings.Secure.getInt(getContentResolver(), "hands_free_message", 0) == 1){        TtsUtil.read(this, getResources().getString(R.string.new_message_from)                                     +getSenderString());        }

    

    3. 来电时的语音播报

    InCallScreen.java中:

    

public String callScreenDisplayName = null;public int mCountTTS;


    onStart()函数中添加:

    

mCountTTS = 0;if(TtsUtil.mTts == null){   TtsUtil.mTts = new TextToSpeech(getApplicationContext(), null);}inComingCallTTS();

    inComingCallTTS()是自己实现的函数(代码大概是用来实现来电几秒钟后开始播报来电信息的):


public void inComingCallTTS() {if (mCountTTS == 3) {return;} else {final HashMap<String, String> myHashAlarm = new HashMap();TelephonyManager tm = (TelephonyManager)this.getApplicationContext()                                                                     .getSystemService(Service.TELEPHONY_SERVICE);myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "end of wakeup message ID");if (Settings.Secure.getInt(getApplicationContext().getContentResolver(), "hands_free_call", 0) == 1                    && tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {Timer mTimer = new Timer();mTimer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stub++mCountTTS;final CallNotifier notifier = mApp.notifier;if (notifier.isRinging()) {notifier.silenceRinger();}TtsUtil.mTts.speak(getApplicationContext().getString(R.string.new_calling_from) + callScreenDisplayName,TextToSpeech.QUEUE_FLUSH, myHashAlarm);// TtsUtil.read(getApplicationContext(),getApplicationContext()                                                                                 .getString(R.string.new_calling_from) + callScreenDisplayName);TtsUtil.mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {@Overridepublic void onUtteranceCompleted(String utteranceId) {// TODO Auto-generated method stubif (utteranceId.equals("end of wakeup message ID")) {notifier.restartRinger();Timer mCountTimer = new Timer();mCountTimer.schedule(new TimerTask() {@Overridepublic void run() {inComingCallTTS();}}, 0 * 1000);}}});}}, 4 * 1000);}}}


    最后,在onStop()函数中添加:mCountTTS= 0;即可。

    就总结到这里了。

    

0 0
原创粉丝点击