TTS在fragment中的实现
public class mouFragment extends Fragment { private EditText mWord; TextToSpeech ttsObject; Button speakButton; int result;//为了方便,可以不用 String text;//为了方便,可以不用 @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tanngo, container, false); ttsObject = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { result = ttsObject.setLanguage(Locale.JAPANESE); } else { Toast.makeText(getActivity(), "FEATURE NOT SUPPORTED IN YOUR DEVICE", Toast.LENGTH_SHORT).show(); } } }); mWord = (EditText) v.findViewById(R.id.tanngo_word); speakButton = (Button) v.findViewById(R.id.speak_button); speakButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.speak_button: if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) { Toast.makeText(getActivity(), "FEATURE NOT SUPPORTED IN YOUR DEVICE", Toast.LENGTH_SHORT).show(); } else { text = mWord.getText().toString();//一定要gettext再tostring,不然会有奇怪的东西出现 ttsObject.speak(text, TextToSpeech.QUEUE_FLUSH, null); } break; } } }); return v; } @Override public void onDestroy() { super.onDestroy(); if (ttsObject != null) { ttsObject.stop(); ttsObject.shutdown(); } }}
废话不多说,先上代码。
在activity中,实现tts播报早已不是什么难事,但是将其搬到fragment中,却总是有很多坑。之前在百度,Google,Stack Overflow和youtobe上看了很多实现tts播报的demo,但是很多都是在activity上做的。在Android开发中,虽然使用activity比较简单,但是在实际运用中,fragment虽然复杂但是却更具灵活性,在开发中会被更多地使用。好了,言归正传。接下来主要讲一下这段代码并说明tts实现播报在fragment和activity中的区别。要实现tts播报主要通过如下几个部分:定义一个TextToSpeech对象
TextToSpeech ttsObject;在TextToSpeech的OnInitListener中设置语言
ttsObject=new TextToSpeech(MainActivity.this,new OnInitListener(){ public void onInit(int status){ //set language} });在OnclickListener中处理error,如果配置正确则speak
if(there is missing data or missing language){ //handle the error }else{ ttsObject.speak(text,TextToSpeech.QUEUE_FLUSH,null); }读完之后释放TextToSpeech engine使用的资源,并停止读
接下来说明tts播报实现在activity和fragment的区别,主要在第二部份的ttsObject = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {...});在activity中,第一个参数可以写为所在activity.this,也可以写为getApplicationContext();在fragment中,只能写为getActivity()。
希望以上内容能在大家的开发中有所帮助。