TTS (텍스트 음성 변환)-Android
나는 안드로이드 플랫폼을 처음 사용합니다. 이제 작업 중입니다 TTS(Text to Speech)
. TextArea에 텍스트를 입력하고 말하기 버튼을 클릭하면 음성으로 변환되기를 원합니다.
누구든지 나를 도울 수 있습니까?
텍스트 음성 변환은 Android 1.6 이상에 내장되어 있습니다. 다음은이를 수행하는 방법에 대한 간단한 예입니다.
TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
추가 정보 : http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html
다음은 Android SDK Manager에서 샘플 코드를 다운로드하는 방법에 대한 안내 입니다.
Android SDK Manager를 시작합니다.
ㅏ. Windows에서는 Android SDK 디렉토리의 루트에있는 SDK Manager.exe 파일을 두 번 클릭합니다.
비. Mac 또는 Linux에서는 Android SDK의 tools / 디렉토리에 대한 터미널을 연 다음 android sdk를 실행합니다.
최신 Android 플랫폼 용 패키지 목록을 확장합니다.
- SDK 용 샘플을 선택하고 다운로드합니다. 다운로드가 완료되면 다음 위치에서 모든 샘플의 소스 코드를 찾을 수 있습니다.
/ sdk / samples / android-version /
(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)
package com.example.texttospeech;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
String text;
EditText et;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.editText1);
tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS){
int result=tts.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("error", "This Language is not supported");
}
else{
ConvertTextToSpeech();
}
}
else
Log.e("error", "Initilization Failed!");
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
public void onClick(View v){
ConvertTextToSpeech();
}
private void ConvertTextToSpeech() {
// TODO Auto-generated method stub
text = et.getText().toString();
if(text==null||"".equals(text))
{
text = "Content not available";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}else
tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="177dp"
android:onClick="onClick"
android:text="Button" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="81dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
이것을 시도하십시오, 그것의 간단한 : ** speakout.xml : **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>
그리고 SpeakOut.java :
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakout);
btnspeakout = (Button) findViewById(R.id.btnspeakout);
edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
repeatTTS = new TextToSpeech(this, this);
btnspeakout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
repeatTTS.speak(edtTexttoSpeak.getText().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
});
}
@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
}
}
TTS 시스템을 빠르게 테스트하기위한 최소한의 예 :
private TextToSpeech textToSpeechSystem;
@Override
protected void onStart() {
super.onStart();
textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
String textToSay = "Hello world, this is a test message!";
textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
현지화 된 메시지를 사용하지 않는 경우 textToSpeechSystem.setLanguage(..)
에도 사용자가 모두 영어를 기본 언어로 설정하지 않았기 때문에 단어의 발음이 잘못 될 수 있기 때문에 중요합니다. 하지만 일반적으로 TTS를 테스트하려면이 스 니펫으로 충분합니다.
관련 링크 : https://developer.android.com/reference/android/speech/tts/TextToSpeech
public class Texttovoice extends ActionBarActivity implements OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_texttovoice);
tts = new TextToSpeech(this, this);
// Refer 'Speak' button
btnSpeak = (Button) findViewById(R.id.btnSpeak);
// Refer 'Text' control
txtText = (EditText) findViewById(R.id.txtText);
// Handle onClick event for button 'Speak'
btnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Method yet to be defined
speakOut();
}
});
}
private void speakOut() {
// Get the text typed
String text = txtText.getText().toString();
// If no text is typed, tts will read out 'You haven't typed text'
// else it reads out the text you typed
if (text.length() == 0) {
tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.texttovoice, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onInit(int status) {
// TODO Auto-generated method stub
// TTS is successfully initialized
if (status == TextToSpeech.SUCCESS) {
// Setting speech language
int result = tts.setLanguage(Locale.US);
// If your device doesn't support language you set above
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Cook simple toast message with message
Toast.makeText(getApplicationContext(), "Language not supported",
Toast.LENGTH_LONG).show();
Log.e("TTS", "Language is not supported");
}
// Enable the button - It was disabled in main.xml (Go back and
// Check it)
else {
btnSpeak.setEnabled(true);
}
// TTS is not initialized properly
} else {
Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
.show();
Log.e("TTS", "Initilization Failed");
}
}
//-------------------------------XML---------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="15dip"
android:text="listen your text"
android:textColor="#0587d9"
android:textSize="26dip"
android:textStyle="bold" />
<EditText
android:id="@+id/txtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:layout_marginTop="20dip"
android:hint="Enter text to speak" />
<Button
android:id="@+id/btnSpeak"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:enabled="false"
android:text="Speak"
android:onClick="speakout"/>
https://drive.google.com/open?id=0BzBKpZ4nzNzUR05nVUI1aVF6N1k
package com.keshav.speechtotextexample;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
====================================================
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_gradient"
android:orientation="vertical">
<TextView
android:id="@+id/txtSpeechInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:textColor="@color/white"
android:textSize="26dp"
android:textStyle="normal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:gravity="center"
android:orientation="vertical">
<ImageButton
android:id="@+id/btnSpeak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:src="@drawable/ico_mic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/tap_on_mic"
android:textColor="@color/white"
android:textSize="15dp"
android:textStyle="normal" />
</LinearLayout>
</RelativeLayout>
===============================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Speech To Text</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="speech_prompt">Say something…</string>
<string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
<string name="tap_on_mic">Tap on mic to speak</string>
</resources>
===============================================================
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
참고URL : https://stackoverflow.com/questions/3058919/text-to-speechtts-android
'UFO ET IT' 카테고리의 다른 글
IE8을 IE7 호환 모드로 강제 설정 (0) | 2020.12.06 |
---|---|
Python에서 AND 및 NOT 연산자 사용 (0) | 2020.12.06 |
Android에서 애플리케이션 설치 날짜 가져 오기 (0) | 2020.12.06 |
Usercontrol에서 이벤트를 만들고 Main Form에서 처리하는 방법은 무엇입니까? (0) | 2020.12.06 |
http와 https의 차이점 (0) | 2020.12.04 |