web-dev-qa-db-ja.com

テキスト読み上げ(TTS)-Android

Androidプラットフォームを初めて使用します。現在、TTS(Text to Speech)に取り組んでいます。TextAreaにテキストを入力して、i話すボタンをクリックします。

誰も私を助けることができますか?

59
bharathi

テキスト読み上げは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マネージャーからサンプルコードをダウンロードする方法について:

  1. Android SDK Managerを起動します。

    a。 Windowsでは、Android SDKディレクトリのルートにあるSDK Manager.exeファイルをダブルクリックします。

    b。 MacまたはLinuxでは、Android SDKのtools /ディレクトリへのターミナルを開き、Android sdk。

  2. 最新のAndroidプラットフォームのパッケージのリストを展開します。

  3. SDKのサンプルを選択してダウンロードします。ダウンロードが完了すると、次の場所ですべてのサンプルのソースコードを見つけることができます。

/ sdk/samples/Android-version /

(i.e. \Android-sdk-windows\samples\Android-16\ApiDemos\src\com\example\Android\apis\app\TextToSpeechActivity.Java)
87
Quantumgeek
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>
58
Sifat Ifty

これを試してみてください:** 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
    }
}

SOURCE Parallelcodes.comの投稿

3
hitesh vikani

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

3
Simon Heinen
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"/>
2

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&#8230;</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>
0
Keshav Gera