1

我試圖使用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); 
    } 
} 

回答

0

這可能是一個評論,我不知道,但你可以嘗試 變化
if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {

if (Text2SpeechCurrentStatus != TextToSpeech.ERROR) {

也許你可以調試,什麼是Text2SpeechCurrentStatus

1

首先,最重要的是:檢查是否有任何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); 
} 

希望它可以幫助...