Text-to-speech
Set up the backend
Run amplify add predictions
, then use the following answers:
1? Please select from one of the categories below2 `Convert`3? What would you like to convert? (Use arrow keys)4 `Generate speech audio from text`5? Provide a friendly name for your resource6 `speechGenerator`7? What is the source language? (Use arrow keys)8 `US English`9? Select a speaker (Use arrow keys)10 `Joanna - Female`11? Who should have access? (Use arrow keys)12 `Auth and Guest users`
Run amplify push
to create the resources in the cloud.
Working with the API
Open MainActivity.java
and add the following code:
1private final MediaPlayer mp = new MediaPlayer();2
3@Override4protected void onCreate(Bundle savedInstanceState) {5 super.onCreate(savedInstanceState);6 setContentView(R.layout.activity_main);7
8 Amplify.Predictions.convertTextToSpeech(9 "I like to eat spaghetti",10 result -> playAudio(result.getAudioData()),11 error -> Log.e("MyAmplifyApp", "Conversion failed", error)12 );13}14
15private void playAudio(InputStream data) {16 File mp3File = new File(getCacheDir(), "audio.mp3");17
18 try (OutputStream out = new FileOutputStream(mp3File)) {19 byte[] buffer = new byte[8 * 1_024];20 int bytesRead;21 while ((bytesRead = data.read(buffer)) != -1) {22 out.write(buffer, 0, bytesRead);23 }24 mp.reset();25 mp.setOnPreparedListener(MediaPlayer::start);26 mp.setDataSource(new FileInputStream(mp3File).getFD());27 mp.prepareAsync();28 } catch (IOException error) {29 Log.e("MyAmplifyApp", "Error writing audio file", error);30 }31}
This example works on all supported versions of Android. Android API 23 added support for MediaDataSource
, which allows for InputStream
from Amplify to be read directly without writing to a file.
As a result of running this code, you will hear audio of the text being emitted from your device.