Skip to content

Instantly share code, notes, and snippets.

@hendrawd
Forked from hbcafe/gist:e6d53488acfdf6ae0fdf81caea0d2dfe
Last active December 29, 2017 04:16
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 hendrawd/8c9b95acb7e794f006b3cc012ec26cda to your computer and use it in GitHub Desktop.
Save hendrawd/8c9b95acb7e794f006b3cc012ec26cda to your computer and use it in GitHub Desktop.
Simpler implementation for connecting native Android app to Watson Text to Speech in under 10 minutes (TTS interface)
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textToSpeak = editText.getText().toString();
System.out.println("the text to speech: " + textToSpeak);
textView.setText("TTS: " + textToSpeak);
new WatsonTask().execute(textToSpeak);
}
});
}
private TextToSpeech initTextToSpeechService() {
TextToSpeech service = new TextToSpeech();
String username = "<your username>";
String password = "<your password>";
service.setUsernameAndPassword(username, password);
return service;
}
private class WatsonTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... textToSpeak) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("running the Watson thread");
}
});
TextToSpeech textToSpeech = initTextToSpeechService();
new StreamPlayer().playStream(textToSpeech.synthesize(String.valueOf(textToSpeak[0]), Voice.EN_MICHAEL).execute());
return "text to speech done";
}
@Override
protected void onPostExecute(String result) {
textView.setText("TTS status: " + result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment