import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private EditText txtText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开启语音识别功能
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//设置模式
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,“en-US”);
//提示语音开始文字
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,“Please start your voice”);
//开始进行语音识别,这里先检测手机(模拟器)是否支持语音识别并且捕获异常
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText(“”);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
“Opps! Your device doesn’t support Speech to Text”,
Toast.LENGTH_SHORT);