본문 바로가기

Android

구글 음성검색을 텍스트화 시키기


public class Speech extends Activity implements OnClickListener {
       private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
       private ListView mList;
       TextView text1;
             
       @Override
       public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
     
        Button speakButton = (Button) findViewById(R.id.btn_speak);
        text1 = (TextView) findViewById(R.id.text);
        mList = (ListView) findViewById(R.id.list);
       
        speakButton.setOnClickListener(this);       
       }
      
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
        startVoiceRecognitionActivity(); //음성검색 실행
        }
    }
   
    //음성검색
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }
   
    //음성검색으로 받아온 데이터
    @Override
    protected void onActivityResult(int requestCode,

                                    int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
       
            ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);           
            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
           
            String str1 = (String) mList.getItemAtPosition(0); //음성인식하여 얻은 문자열
            text1.setText("말한단어 : " + str1);
        }
 

        super.onActivityResult(requestCode, resultCode, data);
    }

출처 : http://tkdcodl.blog.me/20112327596