Android 语音播报实现

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

    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() {
			@Override
			public 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() {
							@Override
							public void onDone(String utteranceId) {
								mTts.stop();
								mTts.shutdown();
							}

							@Override
							public void onError(String utteranceId) {
								mTts.stop();
								mTts.shutdown();
							}

							@Override
							public 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() {

						@Override
						public 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() {

								@Override
								public void onUtteranceCompleted(String utteranceId) {
										// TODO Auto-generated method stub
									if (utteranceId.equals("end of wakeup message ID")) {
										notifier.restartRinger();
										Timer mCountTimer = new Timer();
										mCountTimer.schedule(new TimerTask() {
											
											@Override
											public void run() {
												inComingCallTTS();
											}
										}, 0 * 1000);
									}
								}
							});
						}
					}, 4 * 1000);
			}
		}
	}


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

    就总结到这里了。

    

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值