Notice
Recent Posts
Recent Comments
Today
Total
04-27 02:22
Archives
관리 메뉴

Jeongchul Kim

구글 음성 인식 (SST : Speech to Text) 본문

Android

구글 음성 인식 (SST : Speech to Text)

김 정출 2016. 2. 17. 17:45


구글 음성 인식 (SST : Speech to Text)


오늘은 첫째로 구글 음성 인식을 사용해 보겠습니다.


구글에서 지원하는 음성 인식 지원 기술 SST를 이용하는 액티비티를 만들어 보겠습니다.


MainActivity.Java 와 activity_main.xml 파일이 필요합니다.


AndriodManifest.xml

우선 uses-permission에서 인터넷과 오디오 권한을 설정합니다.

// 음성 인식을 하기 위해 인터넷에 접속 INTERENT 권한

<uses-permission android:name="android.permission.INTERNET"/>

// 음성을 입력받기 위해 RECORD_AUDIO 권한 필요.

<uses-permission android:name="android.permission.RECORD_AUDIO"/>


MainActivity.java

전역 변수부터 살펴보겠습니다.


리퀘스트 코드와 인텐트와 음성 인식 받은 결과인 문자열을 출력하는 텍스트 뷰와 이미지 버튼을 선언합니다.

private static final int RESULT_SPEECH = 1; // REQUEST_CODE로 쓰임

private Intent i;

private TextView tv;

private ImageButton bt;


다음은 onCreate() 함수입니다.

@Override

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);


  final 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)

                  .show();

      }

  });

  /* 레이아웃의 컴포넌트를 가져옵니다.*/

  tv = (TextView) findViewById(R.id.textVeiw);

  bt = (ImageButton) findViewById(R.id.button);

  user_bt = (ImageButton) findViewById(R.id.user_button);


  /* 버튼에 대한 클릭 리스너 등록 부분*/

  bt.setOnClickListener(new View.OnClickListener(){

      @Override

      public void onClick(View v) {

          if(v.getId() == R.id.button) {

              /* Intent 부분*/

              i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // Intent 생성

              i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); // 호출한 패키지

              i.putExtra(RecognizerIntent.EXTRA_LANGUAGE,"ko-KR"); // 인식할 언어를 설정한다.

              i.putExtra(RecognizerIntent.EXTRA_PROMPT, "말해주세요"); // 유저에게 보여줄 문자

              Toast.makeText(MainActivity.this,"start speak",Toast.LENGTH_SHORT).show();

              try {

                  startActivityForResult(i, RESULT_SPEECH);

              }catch(ActivityNotFoundException e) {

                  Toast.makeText(getApplicationContext(),"Speech To Text를 지원하지 않습니다.",Toast.LENGTH_SHORT).show();

                  e.getStackTrace();

              }

          }

      }

  });

}


클릭리스너 마지막 부분이 ActivityResult 호출 부분이 있습니다.

음성인식 결과는 onActivityResult 메소드를 통해 받으며, data.getStringArrayListExtra()메소드를 통해

인식 결과가 ArrayList로 넘어옵니다.

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  super.onActivityResult(requestCode, resultCode, data);

  if(resultCode == RESULT_OK && (requestCode == RESULT_SPEECH)) {

      /* data.getString...() 호출로 음성 인식 결과를 ArrayList로 받는다. */

      ArrayList<String> sstResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

      /* 결과들 중 음성과 가장 유사한 단어부터 시작되는 0번째 문자열을 저장한다.*/

      String result_sst = sstResult.get(0);


      tv.setText("" + result_sst); // 텍스트 뷰에 보여준다.

      Toast.makeText(MainActivity.this,result_sst,Toast.LENGTH_SHORT).show(); // 토스트로 보여준다.

  }

}


전체 소스코드 입니다.

package jeongchul.app.stt.myapplication;


import android.app.Activity;

import android.content.ActivityNotFoundException;

import android.content.Intent;

import android.graphics.Color;

import android.os.Bundle;


import android.speech.RecognitionListener;

import android.speech.RecognizerIntent;

import android.speech.SpeechRecognizer;


import android.speech.tts.TextToSpeech;

import android.support.design.widget.FloatingActionButton;

import android.support.design.widget.Snackbar;

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.ImageButton;

import android.widget.TextView;

import android.widget.Toast;


import java.util.ArrayList;

import java.util.Locale;


public class MainActivity extends Activity{


  private static final int RESULT_SPEECH = 1; // REQUEST_CODE로 쓰임


  private Intent i;

  private TextView tv;

  private ImageButton bt;

  private ImageButton user_bt;


  private SpeechRecognizer mRecognizer;


  TextToSpeech tts;


  @Override

  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);


      final 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)

                      .show();

          }

      });


      /* 레이아웃의 컴포넌트를 가져옵니다.*/

      tv = (TextView) findViewById(R.id.textVeiw);

      bt = (ImageButton) findViewById(R.id.button);

      user_bt = (ImageButton) findViewById(R.id.user_button);




      user_bt.setOnClickListener(new View.OnClickListener() {

          @Override

          public void onClick(View v) {

              if (v.getId() == R.id.user_button) {

;

              }

          }

      });


      /* 버튼에 대한 클릭 리스너 등록 부분*/

      bt.setOnClickListener(new View.OnClickListener(){

          @Override

          public void onClick(View v) {

              if(v.getId() == R.id.button) {

                  /* Intent 부분*/

                  i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // Intent 생성

                  i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); // 호출한 패키지

                  i.putExtra(RecognizerIntent.EXTRA_LANGUAGE,"ko-KR"); // 인식할 언어를 설정한다.

                  i.putExtra(RecognizerIntent.EXTRA_PROMPT, "말해주세요"); // 유저에게 보여줄 문자


                  Toast.makeText(MainActivity.this,"start speak",Toast.LENGTH_SHORT).show();


                  try {

                      startActivityForResult(i, RESULT_SPEECH);

                  }catch(ActivityNotFoundException e) {

                      Toast.makeText(getApplicationContext(),"Speech To Text를 지원하지 않습니다.",Toast.LENGTH_SHORT).show();

                      e.getStackTrace();

                  }


              }

          }

      });

  }



  @Override

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      super.onActivityResult(requestCode, resultCode, data);

      if(resultCode == RESULT_OK && (requestCode == RESULT_SPEECH)) {


          /* data.getString...() 호출로 음성 인식 결과를 ArrayList로 받는다. */

          ArrayList<String> sstResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);


          /* 결과들 중 음성과 가장 유사한 단어부터 시작되는 0번째 문자열을 저장한다.*/

          String result_sst = sstResult.get(0);


          tv.setText("" + result_sst); // 텍스트 뷰에 보여준다.


          Toast.makeText(MainActivity.this,result_sst,Toast.LENGTH_SHORT).show(); // 토스트로 보여준다.

      }

  }


  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

      // Inflate the menu; this adds items to the action bar if it is present.

      getMenuInflater().inflate(R.menu.menu_main, menu);

      return true;

  }


  @Override

  public boolean onOptionsItemSelected(MenuItem item) {

      // Handle action bar item clicks here. The action bar will

      // automatically handle clicks on the Home/Up button, so long

      // as you specify a parent activity in AndroidManifest.xml.

      int id = item.getItemId();


      //noinspection SimplifiableIfStatement

      if (id == R.id.action_settings) {

          return true;

      }


      return super.onOptionsItemSelected(item);

  }

}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"

  xmlns:app="http://schemas.android.com/apk/res-auto"

  xmlns:tools="http://schemas.android.com/tools"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:fitsSystemWindows="true"

  android:background="@drawable/bg_gradient"

  tools:context="jeongchul.app.stt.myapplication.MainActivity">


  <LinearLayout

      android:gravity="center"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:orientation="vertical">



      <TextView

          android:id="@+id/textVeiw"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:text=""

          android:textColor="@color/white"

          android:textSize="15dp"/>

      <ImageButton

          android:id="@+id/button"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:src="@drawable/ico_mic" />

      <TextView

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:layout_marginTop="10dp"

          android:text="Google SST"

          android:textColor="@color/white"

          android:textSize="15dp"

          android:textStyle="normal" />


      <ImageButton

          android:layout_marginTop="30dp"

          android:id="@+id/user_button"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:src="@drawable/ico_mic" />

      <TextView

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:layout_marginTop="10dp"

          android:text="User SST"

          android:textColor="@color/white"

          android:textSize="15dp"

          android:textStyle="normal" />

  </LinearLayout>


  <android.support.design.widget.FloatingActionButton

      android:id="@+id/fab"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:layout_gravity="bottom|end"

      android:layout_margin="@dimen/fab_margin"

      android:src="@android:drawable/ic_btn_speak_now"

      />

</android.support.design.widget.CoordinatorLayout>


res/drawable/bg_gradient.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">

  <gradient

      android:startColor="@color/bg_gradient_start"

      android:endColor= "@color/bg_gradient_end"

      android:angle="45"/>

</shape>


res/drawable/ico_mic.png

또는 google에 mic icon 이미지를 검색해서 png 아이콘을 저장하시기 바랍니다.


res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

  <color name="colorAccent">#FF4081</color>

  <color name="bg_gradient_start">#31244e</color>

  <color name="bg_gradient_end">#6b394c</color>

  <color name="white">#ffffff</color>

</resources>



다음장에서는 User inter

Comments