- 主功能的部分实现代码:
- public class MainActivity extends Activity {
-
- protected static final int RESULT_SPEECH = 1;
- private ImageButton btnSpeak;
- private TextView txtText;
- public static int status=0; //识别结束状态
- protected void speech_send(){
- Intent intent = new Intent(
- RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US"); //加载离线语音包,以默认安装包为准
-
-
- try {
- startActivityForResult(intent, RESULT_SPEECH);
- //txtText.setText("");
-
- } catch (ActivityNotFoundException a) {
- Toast t = Toast.makeText(getApplicationContext(),
- "Ops! Your device doesn't support Speech to Text",
- Toast.LENGTH_SHORT);
- t.show();
- }
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- txtText = (TextView) findViewById(R.id.txtText);
- btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
- btnSpeak.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- speech_send();
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
-
- switch (requestCode) {
- case RESULT_SPEECH: {
- if (resultCode == RESULT_OK && null != data) {
- ArrayList<String> text = data
- .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
- String str1= text.get(0);
- String str2 = PinYin.getPinYin(str1); //汉字转拼音
- if(str2.indexOf("lao")>-1||str2.contains("3")||str2.indexOf("sha")>-1
- ||str2.indexOf("ang")>-1||str2.indexOf("an")>-1){ //自定义拼音字母模糊匹配
- str2="上";
- }
- if(str2.contains("x")||str2.indexOf("ia")>-1){
- str2="下";
- }
- if( str2=="o" || str2.indexOf("siwa")>-1||str2.contains("z")
- ||str2.indexOf("uo")>-1 ||str2.indexOf("wo")>-1){
- str2="左";
- }
- if(str2.contains("y")||str2.indexOf("iu")>-1||str2.indexOf("ou")>-1
- ||str2.contains("1")){
- str2="右";
- }
- txtText.setText(str2);
- status=1;
-
- }
- break;
- }
- }
-
- if(status==1){ //重复语音识别
- speech_send();
- status=0;
- }
- }
- }
复制代码
|