티스토리 뷰

Android/실전 TIP

음성 인식

Dev-Drake 2019. 3. 29. 11:55
반응형

// main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
<EditText
 android:id     = "@+id/EdtName"
 android:layout_width  = "fill_parent"
 android:layout_height = "wrap_content"
/>

<Button
  android:id    = "@+id/BtnSpeech"
  android:layout_width = "fill_parent" 
  android:layout_height = "50px" 
  android:text   = "음성 인식"
></Button>

</LinearLayout>

 

 

 // SpeechToTextActivity.java

package pkg.SpeechToText;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SpeechToTextActivity extends Activity {
 private static final int REQUEST_CODE = 0;
 private EditText mEdit;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mEdit = (EditText)findViewById(R.id.EdtName);
        findViewById(R.id.BtnSpeech).setOnClickListener(mClick);

    }
    
    Button.OnClickListener mClick = new View.OnClickListener() {
     @Override
     public void onClick(View v) {
      switch(v.getId()) {
       case R.id.BtnSpeech  :

       try {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "SpeechToTextActivity");
        startActivityForResult(intent, REQUEST_CODE);
       } catch(ActivityNotFoundException e){
          Toast.makeText(this, "음성 인식 실 패 !!", Toast.LENGTH_SHORT).show();
       }

             break;
      }
     } 
    };

 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
      String str = "";
      
      ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
      
      /*
      for(int i = 0; i < results.size(); i ++){
       str += results.get(i);
      }
      */
      
      str = results.get(0);
      mEdit.setText(str);
     }
    
     super.onActivityResult(requestCode, resultCode, data);
    }   
}

 

반응형

'Android > 실전 TIP' 카테고리의 다른 글

종료 처리  (0) 2019.04.04
앱 이름 설정  (0) 2019.04.04
이미지 뷰 ImageView  (0) 2019.03.29
WAV파일 재생  (0) 2019.03.29
탭 이동시 이벤트  (0) 2019.03.29
댓글
반응형
최근에 올라온 글
Total
Today
Yesterday