如何在Android中获取谷歌默认的tts语言

时间:2015-07-10 12:38:59

标签: android google-text-to-speech

我已经将google tts语言设置为hindi。在我的代码中我将tind.setLanguage(Locale.getDefault())设置为默认语言,我的代码工作正常。但是当我使用Locale.getDefault时()。getDisplayLanguage()获取默认语言,logcat显示英文。 我想根据用户设置语言。     package com.example.texttospeech;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;

import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


@SuppressWarnings("unused")
public class MainActivity extends Activity implements   TextToSpeech.OnInitListener{

    private TextToSpeech tts;

    EditText ed1,ed2;
    Button b1,b2;
    AudioManager audioManager;
    static final int READ_BLOCK_SIZE = 100;
    protected static final int PICKFILE_RESULT_CODE = 1;
    protected static final int ACTIVITY_TTS_PASS=1;

    @SuppressWarnings("static-access")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed1=(EditText)findViewById(R.id.editText1);
        b1=(Button)findViewById(R.id.button1);          
        ed2=(EditText)findViewById(R.id.editText2);
        b2=(Button)findViewById(R.id.button2);   

        tts = new TextToSpeech(this, this);

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int amStreamMusicMaxVol =     audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
        audioManager.setStreamVolume(audioManager.STREAM_MUSIC,     amStreamMusicMaxVol, 0);
        audioManager.setSpeakerphoneOn(true);

        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),    "clicked",Toast.LENGTH_SHORT).show();
            try {
                    if(ed1.getText().toString()==null ||     ed1.getText().toString().matches(""))
                    {
                        Intent intent = new  Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("file.txt/*");
                        startActivityForResult(intent,PICKFILE_RESULT_CODE);
                    }else
                    {
                        savefile();
                    }

                } catch (IOException e) {

                    e.printStackTrace();
                }
            }

        });
        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

//                      openfile();
            }

        });



    }


    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
         super.onDestroy();
    } 


    @Override
    public void onInit(int status) {

        Locale.getDefault().getDisplayLanguage();
        Log.e("--f----f-----f-- ",""+Locale.getDefault().getDisplayLanguage());

      if (status == TextToSpeech.SUCCESS) 
      {

          int result = tts.setLanguage(Locale.getDefault()); 
          Log.e("--g----g-----g--",""+result);
            tts.setLanguage(new Locale("hi_IN"));

             if (result == TextToSpeech.LANG_MISSING_DATA
                     || result == TextToSpeech.LANG_NOT_SUPPORTED) 
             {
             Log.e("TTS", "This Language is not supported");
             }     
             else {
                    b1.setEnabled(true);
                    try {
                            savefile();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }

            } else {
                Log.e("TTS", "Initilization Failed!");
             }

    }

       @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    private void savefile() throws IOException {

     String text = ed1.getText().toString();    
     FileOutputStream fos = null;

     final File dir = new   File(Environment.getExternalStorageDirectory().getAbsolutePath() +
             "/MynewText/" );

     if (!dir.exists())
     {
         dir.mkdirs(); 
     }      

     final File myFile = new File(dir, "newtest" + ".txt");

     if (!myFile.exists()) 
     {    
         myFile.createNewFile();
     } 

     fos = new FileOutputStream(myFile);

     fos.write(text.getBytes());
     fos.close();
     Toast.makeText(getBaseContext(), "File saved     successfully!",Toast.LENGTH_SHORT).show();

     tts.setSpeechRate(0);
     tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    try {               
          // Read text from file       
           File sdcard = Environment.getExternalStorageDirectory();
           File file1 = new File(sdcard,"MynewText/newtest.txt");   

          //Read text from file
          StringBuilder text1 = new StringBuilder();    
          BufferedReader br = new BufferedReader(new FileReader(file1));
          String line;

           while ((line = br.readLine()) != null) 
           {
              text1.append(line);
              text1.append('\n');
            }
           ed2.setText(text1);
           br.close();

        } catch (FileNotFoundException e) 
          {             
             e.printStackTrace();
          }

    }

       @SuppressWarnings("deprecation")
    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent   data) 
{       
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) 
    {
       case ACTIVITY_TTS_PASS:
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) 
       {
          tts = new TextToSpeech(getApplicationContext(), this);
          int availability = tts.isLanguageAvailable(new Locale("hin-IND"));

         switch(availability) 
         {
              case TextToSpeech.LANG_AVAILABLE:
          Log.d("TTS", "Language available");
          break;

          case TextToSpeech.LANG_NOT_SUPPORTED:
          Log.d("TTS", "Language not supported");

          Intent installTTSIntent = new Intent();
          installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
          ArrayList<String> languages = new ArrayList<String>();
          languages.add("hin-IND"); // hin - hindi, IND - INDIA
          installTTSIntent.putStringArrayListExtra(
                  TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR,     languages);
          startActivity(installTTSIntent);
          break;

          case TextToSpeech.LANG_MISSING_DATA:
          Log.d("TTS", "Language missing data");
          break;

          case TextToSpeech.LANG_COUNTRY_AVAILABLE:
          Log.d("TTS", "Contry available");
          break;

          default:
          Log.d("TTS", "default");
       }
      }
      else {
              Log.d("TTS", "fail");
              Intent installTTSIntent = new Intent();
            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
              ArrayList<String> languages = new ArrayList<String>();
              languages.add("hin-IND"); // hin - hindi, IND - INDIA
              installTTSIntent.putStringArrayListExtra(
                           TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR,    languages);
               startActivity(installTTSIntent);
           }

           break;
           default:
           Log.d("TTS", "case default");
           break;
    }
            super.onActivityResult(requestCode, resultCode, data);
  }    
}

1 个答案:

答案 0 :(得分:0)

在设置&gt;中设置默认语言语言和输入&gt;我使用了Google-Text-To-Speech默认语言集:

tts.getLanguage();