我正在开发一个项目,当TextToSpeech函数完成消息时,需要通过振动发出警报。我已经实现了TextToSpeech函数,并知道如何创建振动,但我不知道在哪里编码振动。另外,我遇到的关于如何实现OnUtteranceCompleted方法的例子让我无可救药地困惑。任何人都可以帮我把OnUtteranceCompleted功能放在一起,以及在哪里插入振动代码?这是我的代码:
public class TypeNewMessageActivity extends Activity实现TextToSpeech.OnInitListener {
Button playButton;
EditText typeNewMessageEditText;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_new_message);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
playButton = (Button)findViewById(R.id.playButton);
typeNewMessageEditText = (EditText)findViewById(R.id.typeNewMessageEditText);
tts = new TextToSpeech (this, this);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
playText();
}
});
}
public void onDestroy(){
if (tts != null){
tts.stop();
tts.shutdown();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("tts", "This language is not supported");
}else{
playButton.setEnabled(true);
playText();
}
}else{
Log.e("tts", "Initialized failed");
}
}
public void playText(){
String text = typeNewMessageEditText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
答案 0 :(得分:1)
如果你想在playText()完成讲话时振动,那么改变如下
public void playText(){
String text = typeNewMessageEditText.getText().toString();
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, myHashRender);
}
然后
@Override
public void onUtteranceCompleted(String utteranceId)
{
// code to vibrate.
}