Android文本到语音

问题描述:

我试图使用TextToSpeech类来说我的应用程序中的文本。当我运行我的代码时,我什么都没听到,音量很高。我的代码有什么问题?我需要许可或任何东西吗?Android文本到语音

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener { 

    TextToSpeech textToSpeech; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     textToSpeech = new TextToSpeech(this, this); 

     speakOut(); 
    } 

    @Override 
    public void onInit(int Text2SpeechCurrentStatus) { 

     if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) { 

      int result = textToSpeech.setLanguage(Locale.US); 

      if (result == TextToSpeech.LANG_MISSING_DATA 
        || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
       Log.e("TTS", "This Language is not supported"); 
      } else { 
       speakOut(); 
      } 

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

    private void speakOut() { 
     String g= "Hello"; 
     textToSpeech.speak(g, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 

这可能是一个评论,我不知道,但你可以尝试 变化
if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {

if (Text2SpeechCurrentStatus != TextToSpeech.ERROR) {

也许你可以调试,什么是Text2SpeechCurrentStatus

首先,最重要的是:检查是否有任何TTS引擎安装在您的设备中。

并且不,您不需要任何使用TTS的权限。

在此活动的onCreate()方法中初始化TextToSpeech实例。

TextToSpeech t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { 
    @Override 
    public void onInit(int status) { 
     if(status != TextToSpeech.ERROR) { 
      t1.setLanguage(Locale.UK); 
     } 
    } 
    }); 

//这是您的speakOut()方法。

private void speakOut() { 
    String g= "Hello"; 
    t1.speak(g, TextToSpeech.QUEUE_FLUSH, null); 
} 

希望它可以帮助...