android调用tts接口,Android在BroadcastReceiver中调用TTS

我需要在BroadcastReceiver的子类中调用TTS服务.当我从OnInitListener实现该类时,它给出了运行时错误.

在BroadcastReceiver中是否有其他方式来实现TTS?

谢谢,

对不起代码:

public class TextApp extends BroadcastReceiver implements OnInitListener {

private TextToSpeech tts;

private String message = "Hello";

@Override

public void onReceive(Context context, Intent intent) {

tts = new TextToSpeech(context, this);

message = "Hello TTS";

}

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS)

{

tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);

}

}

}

最佳答案:

您的代码无效:

tts = new TextToSpeech(context, this);

BroadcastReceiver上的上下文是“受限上下文”.这意味着您无法在BroadcastReceiver中启动上下文服务.因为TTS是一项服务,所以它不会调用任何东西.

最佳解决方案是您通过调用服务的活动开始对BroadcastReceiver的另一个意图.

public void onReceive(Context context, Intent intent) {

....

Intent speechIntent = new Intent();

speechIntent.setClass(context, ReadTheMessage.class);

speechIntent.putExtra("MESSAGE", message.getMessageBody().toString());

speechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

context.startActivity(speechIntent);

....

}

然后在活动中使用附加参数调用TTS服务

public class ReadTheMessage extends Activity implements OnInitListener,OnUtteranceCompletedListener {

private TextToSpeech tts = null;

private String msg = "";

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Intent startingIntent = this.getIntent();

msg = startingIntent.getStringExtra("MESSAGE");

tts = new TextToSpeech(this,this);

}

@Override

protected void onDestroy() {

super.onDestroy();

if (tts!=null) {

tts.shutdown();

}

}

// OnInitListener impl

public void onInit(int status) {

tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);

}

// OnUtteranceCompletedListener impl

public void onUtteranceCompleted(String utteranceId) {

tts.shutdown();

tts = null;

finish();

}

}

标签:android,text-to-speech

来源: https://codeday.me/bug/20190515/1109987.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值