c# - 如果从任何生命周期方法运行,Xamarin Android TextToSpeech.Speak 什么也不说
问题描述
我正在使用 TextToSpeech 的一个实例来转换一些文本,使用 Speak() 方法,如下所示:
textToSpeech = new TextToSpeech(context, this, "com.google.android.tts");
textToSpeech.SetPitch(1f);
textToSpeech.SetSpeechRate(1f);
textToSpeech.Speak(textToConvert, QueueMode.Flush, null, null);
该函数运行良好,没有错误,但只有在没有从生命周期方法调用该函数时才能真正听到语音(并且 isSpeaking 属性仅更改为 true)。
我尝试将它放在 OnCreate()、OnStart() 和 OnResume() 中,结果都相同,尽管如果从按钮事件调用该函数运行良好。
这是课程的限制,还是我可以解决的问题?
解决方案
这是因为您在 TTS 引擎加载之前调用了 Speak() 方法。它需要一些时间来初始化。
幸运的是,TextToSpeech.IOnInitListener 接口提供了一种通过 OnInit() 方法了解引擎何时成功加载的方法。
因此,如果您希望您的应用程序在 OnCreate() 中说话,则需要将 Speak() 方法移至 OnInit() 方法。这是我为您整理的一个工作示例...
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Speech.Tts;
namespace XamdroidMaster.Activities {
[Activity(ParentActivity = typeof(MainActivity), Label = "Text to Speech")]
public class TextToSpeechActivity : Activity, TextToSpeech.IOnInitListener {
private TextToSpeech tts;
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.TextToSpeech);
// Create text to speech object (first parameter: context; second parameter: object implementing TextToSpeech.IOnInitListener)
// Note that it may take a few moments for the TTS engine to initialize (OnInit() will fire when it's ready)
tts = new TextToSpeech(this, this, "com.google.android.tts");
}
public void OnInit([GeneratedEnum] OperationResult status) {
if (status == OperationResult.Success) {
tts.SetPitch(1f);
tts.SetSpeechRate(1f);
tts.Speak("Hello Luke!", QueueMode.Flush, null);
}
}
}
}
此外,通过在 OnCreate() 中初始化 TTS 引擎,如我在示例中所示,您应该能够稍后在 OnResume() 中触发 Speak() 命令。
希望这可以帮助!
推荐阅读
- java - PassiveExpiringMap 没有过期的对象
- jquery - 使用 Power Query 通过 REST API 查询分页 XML
- xcode - 如何在 Azure Pipelines 中升级 XCode?
- html - 'counter-reset' 属性是否总是必须在父容器上定义?
- c# - 在不相关的组件上调用 OnSetParameterAsync
- javascript - 如何在 Nodejs 中使用对象
- python - groupby 变换的长度不匹配错误
- amazon-web-services - Amplify 无法使用 Amplify 识别预先存在的 Vue.js 项目
- ios - SwiftUI 不一致的行为从 SwiftUI 视图“推送”到 UIKit ViewController
- node.js - 如何创建一个不断检查我的 firebase 数据库的 NodeJS 应用程序