2017. 7. 23. 16:43ㆍAndroid
위키피디아에 따르면, 음성 인식(Speech Recognition)이란 사람이 말하는 음성 언어를 컴퓨터가 해석해 그 내용을 문자 데이터로 전환하는 처리를 말한다.
STT(Speech-to-Text)라고도 한다.
Android Studio에서 STT를 사용하는 방법은 다양하지만, 이번 예제는 단순히 구글 음성인식 앱을 실행시켜 결과값을 반환하는 방법이다.
이 방법은 사용하기는 편하지만 개발자가 원하는 UI를 구현하지 못한다.
따라서, 애플리케이션 용도에 맞는 방식으로 음성인식 기술을 구현하기 위해 개발자가 음성인식 이벤트를 일일이 설정해주는 방식이 있다.
음성 입력 시작 및 종료, 음성 인식 성공 및 실패와 같은 이벤트가 발생할 때마다 어떻게 작동할지 설정해주면 된다.
AndroidManifest.xml
인터넷과 네트워크가 연결됐는지 확인하기위해 Manifest에 permission을 추가해준다.
android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> | cs |
activity_main.xml
구글 음성인식을 시작할 버튼과 인식한 음성을 문자로 출력할 TextView가 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/welcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:layout_gravity="center" android:text="Speech Recognition" /> <Button android:id="@+id/start_reg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Start Speech Recognition" /> <TextView android:id="@+id/speech" android:textSize="25sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout> | cs |
dialog_matches_frag.xml
음성인식 결과는 onActivityResult 메소드를 통해서 받게 되고 결과는 ArrayList 형태로 넘어오게 된다.
이 결과들을 다이얼로그로 나타나게 해서 사용자가 고를 수 있게 한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> | cs |
MainActivity.java
음성인식을 시작하려면 버튼을 누르는데
구글 음성인식이 인터넷에 연결이 돼있어야 작동하기 때문에 isConnected() 메소드로 인터넷에 연결됐는지 확인한다.
인터넷에 연결이 돼있으면 Speech Recognizer Intent가 열려서 사용자의 음성을 듣기 시작한다.
사용자의 음성이 인식됐으면 RESULT_OK로 결과값을 반환하고, 새 다이얼로그를 열어 리스트로 반환되는 음성인식 결과들을 출력한다.
이 결과들 중에서 사용자가 선택한 결과를 메인 Activity에 출력을 해준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | package ; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends Activity { private static final int REQUEST_CODE = 1234; Button Start; TextView Speech; Dialog match_text_dialog; ListView textlist; ArrayList<String> matches_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Start = (Button)findViewById(R.id.start_reg); Speech = (TextView)findViewById(R.id.speech); Start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isConnected()){ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); startActivityForResult(intent, REQUEST_CODE); } else{ Toast.makeText(getApplicationContext(), "Plese Connect to Internet", Toast.LENGTH_LONG).show(); }} }); } public boolean isConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo net = cm.getActiveNetworkInfo(); if (net!=null && net.isAvailable() && net.isConnected()) { return true; } else { return false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { match_text_dialog = new Dialog(MainActivity.this); match_text_dialog.setContentView(R.layout.dialog_matches_frag); match_text_dialog.setTitle("Select Matching Text"); textlist = (ListView)match_text_dialog.findViewById(R.id.list); matches_text = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches_text); textlist.setAdapter(adapter); textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Speech.setText("You have said " + matches_text.get(position)); match_text_dialog.hide(); } }); match_text_dialog.show(); } super.onActivityResult(requestCode, resultCode, data); } } | cs |
앱 실행화면
출처 : https://www.learn2crack.com/2013/12/android-speech-recognition-example.html
'Android' 카테고리의 다른 글
[Global SW 공모대전] README 이미지 (0) | 2017.12.04 |
---|---|
[서울시 앱 공모전 / 서울시를 이겨라] ViewPager with fragments (0) | 2017.11.24 |
[서울시 앱 공모전 / 서울시를 이겨라] 서울 열린데이터 광장 Open API 사용 / AsyncTask / Parsing (0) | 2017.11.22 |
[서울시 앱 공모전 / 서울시를 이겨라] BottonNavigationView (1) | 2017.11.18 |
[서울시 앱 공모전 / 서울시를 이겨라] README 이미지 (0) | 2017.11.06 |