Skip to content

Instantly share code, notes, and snippets.

@tmk815
Created December 18, 2016 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmk815/703f09cc23d55733633fffca80df5cd1 to your computer and use it in GitHub Desktop.
Save tmk815/703f09cc23d55733633fffca80df5cd1 to your computer and use it in GitHub Desktop.
TextToSpeech_Sample
<?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:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/action_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="読み上げ" />
</LinearLayout>
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
TextToSpeech tts;
String contents = "読み上げたい内容";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
Button btn = (Button) findViewById(R.id.action_read);
btn.setOnClickListener(new View.OnClickListener() {
//ボタンクリック時
public void onClick(View v) {
if (v.getId() == R.id.action_read) {
speechText();
}
}
});
}
@Override
public void onInit(int status) {
if (TextToSpeech.SUCCESS == status) {
//言語選択
Locale locale = Locale.JAPAN;
if (tts.isLanguageAvailable(locale) >= TextToSpeech.LANG_AVAILABLE) {
tts.setLanguage(locale);
} else {
Log.d("Error", "Locale");
}
} else {
Log.d("Error", "Init");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != tts) {
//ttsのリソース解放する
tts.shutdown();
}
}
private void speechText() {
if (0 < contents.length()) {
if (tts.isSpeaking()) {
// 読み上げ中なら停止
tts.stop();
}
//読み上げられているテキストを確認
System.out.println(contents);
//読み上げ開始
tts.speak(contents, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment