我正在使用TextToSpeech类来使系统说话。 首先,我通过语音识别器说话并将文本设置为textView。接下来我希望系统说出我之前说的话。 我发现第一步是成功的,但在我发言后我没有听到任何声音。
我的代码如下:
public class MainActivity extends AppCompatActivity {
private int REQUEST_CODE=1;
TextView text;
ImageButton button;
TextToSpeech textToSpeech;
private Button ttsButton;
private ArrayList<String> results;
private String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
button=(ImageButton)findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, REQUEST_CODE);
}
});
textToSpeech =new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS)
textToSpeech.setLanguage(Locale.US);
}
});
textToSpeech.speak(s, TextToSpeech.QUEUE_FLUSH, null,null);
}
public void onPause(){
if(textToSpeech !=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onPause();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
s=results.get(0);
text=(TextView)findViewById(R.id.text);
text.setText(""+results.get(0));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
答案 0 :(得分:1)
您忘记在活动结果后触发TTS引擎: -
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
s=results.get(0);
text=(TextView)findViewById(R.id.text);
text.setText(""+results.get(0));
//Trigger text to speech here
textToSpeech.speak(results.get(0), TextToSpeech.QUEUE_FLUSH, null,null);
}
super.onActivityResult(requestCode, resultCode, data);
}