Java – Android TextToSpeech.synthesizeToFile() file is not created

Android TextToSpeech.synthesizeToFile() file is not created… here is a solution to the problem.

Android TextToSpeech.synthesizeToFile() file is not created

I’m trying to implement pause and play functionality for some text using tts and MediaPlayer. However, it seems that I can’t create a .wav file using the synthesizeToFile function.

I’ve added the required permissions in the xml file:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the file creation method I am currently using :

private String envPath = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/Download";
private Uri fileUri;

public void fileCreate() {
    String inputText = output.getText().toString();

HashMap<String, String> myHashRender = new HashMap<String, String>();
    myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, inputText);
    Log.d(TAG, "successfully created hashmap");

String destFileName = envPath + "/" + "tts_file.wav";

int sr = tts.synthesizeToFile(inputText, myHashRender, destFileName);
    Log.d(TAG, "synthesize returns = " + sr);
    File fileTTS = new File(destFileName);

if (fileTTS.exists()) {
        Log.d(TAG, "successfully created fileTTS");
    }
    else {
        Log.d(TAG, "failed while creating fileTTS");
    }

fileUri = Uri.fromFile(fileTTS);
    Log.d(TAG, "successfully created uri link: " + fileUri.getPath());
}

This is how I created the media player :

fileCreate();
    mp = MediaPlayer.create(this, fileUri);
    Log.d(TAG, "successfuly created mediaplayer");

btnRead.setOnClickListener(new OnClickListener() {

@Override
        public void onClick(View arg0) {
            if (mp.isPlaying()) {
                mp.pause();
                Log.d(TAG, "successfully paused");
            } else {
                mp.start();
                Log.d(TAG, "successfully started");
            }
        }

});

Any ideas?

Solution

The synthesizeToFile method is asynchronous, so you should check it

File fileTTS = new File(destFileName);

if (fileTTS.exists()) {
    Log.d(TAG, "successfully created fileTTS");
}
else {
    Log.d(TAG, "failed while creating fileTTS");
}

onUtteranceCompletedListenerUtteranceProgressListener

Related Problems and Solutions