3

I am using the following code to store Text to Speech output as wav file in my application. I am not sure where is the error, can you please take a look into that and suggest me?

public class MainActivity extends Activity {

Button store, play;
EditText input;
String speakTextTxt;
TextToSpeech mTts;
HashMap<String, String> myHashRender = new HashMap<String, String>();
String tempDestFile ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    store = (Button) findViewById(R.id.button1);
    play = (Button) findViewById(R.id.button2);
    input = (EditText) findViewById(R.id.editText1);
    store.setOnClickListener(new OnClickListener()  {

        public void onClick(View v) {
            speakTextTxt = "Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world";
            HashMap<String, String> myHashRender = new HashMap<String, String>();
            myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speakTextTxt);

            String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();

            File appTmpPath = new File(exStoragePath + "/sounds/");
            appTmpPath.mkdirs();

            String tempFilename = "hello.mp3";

            tempDestFile = appTmpPath.getAbsolutePath() + "/" + tempFilename;

            new MySpeech(speakTextTxt);


        }
    });
}

class MySpeech implements OnInitListener
{

            String tts;

    public MySpeech(String tts)
    {
        this.tts = tts;
        mTts = new TextToSpeech(MainActivity.this, this);
    }

    @Override
    public void onInit(int status) 
    {
        Log.v("log", "initi");
        int i = mTts.synthesizeToFile(speakTextTxt, myHashRender, tempDestFile);
        if(i == TextToSpeech.SUCCESS)
        {

          Toast toast = Toast.makeText(MainActivity.this, "Saved "+i,
                Toast.LENGTH_SHORT);
          toast.show();   
        }
        System.out.println("Result : " + i);
    }
  }

 }
Sekhar Bhetalam
  • 4,501
  • 6
  • 33
  • 52
  • @ChandraSekhar File appTmpPath = new File(exStoragePath + "/sekhar/"); ... tempDestFile = appTmpPath.getAbsolutePath() + "/"+ tempFilename; Aren't there two '//' in your file name? – sinisha Feb 04 '13 at 09:26
  • @sinisha, By mistake I added it multiple times. Now I removed and tried. I got the toast from onInIt method which is in subclass. Now I how can i check wehter it is saved or not. I connected my device to my machine and checked the sekhar folder. But there is no wav file. Can you please suggest me? I printed the value of "i" which is 0. – Sekhar Bhetalam Feb 04 '13 at 09:33
  • what text your instance of `MySpeach`did spoken ?? – Houcine Feb 04 '13 at 09:38
  • @Houcine, it should spoke what I give to as input in the EditText – Sekhar Bhetalam Feb 04 '13 at 09:41
  • @ChandraSekhar : but i can't see any instruction in your code above that tell your instance to speak the text from the `EditText` – Houcine Feb 04 '13 at 09:43
  • @Houcine, Here I am trying to generate an audio file from the tts output. I am not trying to play the speech. In the above example I am trying to create a wav file by using the tts output. Unfortunately I am unable to see where that file located. I checked the folder "sekhar" where I was trying to store. But there is no file. – Sekhar Bhetalam Feb 04 '13 at 09:45
  • @ChandraSekhar If in int `i = mTts.synthesizeToFile(speakTextTxt, myHashRender, tempDestFile);` you get i=0 it means operation was successful. Have you entered anything in EditText field? – sinisha Feb 04 '13 at 09:46
  • @sinisha, Yes I entered text. After the toast appeared, I connected my device to my pc and checked for the file name which I try to store. Unfortunately there is no file with this name. – Sekhar Bhetalam Feb 04 '13 at 09:48
  • @ChandraSekhar `String tempFilename = input.getText().toString()+".wav";` Try to replace it with something simple like `tempFileName = "test.wav"` for testing – sinisha Feb 04 '13 at 09:55
  • @sinisha, I tried it as you suggested, but it didn't work. Can you just check my flow What i am doing, I created an application at 2.1 and debugging it using 2.1 device. After storing the file I am checking the sd card directly from my pc. Is this flow is correct? Please confirm. – Sekhar Bhetalam Feb 04 '13 at 10:03
  • @ChandraSekhar It's corect. Do you have following permission `` – sinisha Feb 04 '13 at 10:09
  • @sinisha, Yes I have. If you don't mind can you pleaes share code snippet for this feature if you have. – Sekhar Bhetalam Feb 04 '13 at 10:10
  • @ChandraSekhar The link [link](http://stackoverflow.com/questions/7132673/how-can-i-allow-the-tts-to-write-files-to-my-apps-directories?lq=1) suggests there are problems in saving synthetized text to file – sinisha Feb 04 '13 at 10:32
  • @sinisha, Thanks for your help, At last I am done with that. But the file size is 0kb. Can you advice me on this?? – Sekhar Bhetalam Feb 04 '13 at 11:33

2 Answers2

10

referring to the answer of Ted Hopp in this post :

The important method is synthesizeToFile. It will write the audio to a file on the device that you specify. You can then play that file with a MediaPlayer or you can pull it off the device onto your development system with the adb command-line tool using the command

EDIT :

try this code , and then check the path sdcard/ if it contains the file : test.wav

HashMap<String, String> myHashRender = new HashMap();
String textToConvert = "this is a demo for saving a WAV file";
String destinationFileName = "/sdcard/test.wav";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, textToConvert);
mTts.synthesizeToFile(textToConvert, myHashRender, destinationFileName);

EDIT 2 :

and if you are trying to save the wave file to the internal memory ( not the /sdcard/folder) , then the only way to achieve this is to create a world writable directory in the internal memory like this:

context.getDir("soundfiles", Context.MODE_WORLD_WRITEABLE);

And then write to this dir.

EDIT 3 :

after taking a look into your code , you've just some problems with creating directories and files : the code should be like this :

speakTextTxt = "Hello world";
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speakTextTxt);

String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.d("MainActivity", "exStoragePath : "+exStoragePath);
File appTmpPath = new File(exStoragePath + "/sounds/");
boolean isDirectoryCreated = appTmpPath.mkdirs();
Log.d("MainActivity", "directory "+appTmpPath+" is created : "+isDirectoryCreated);
String tempFilename = "tmpaudio.wav";
tempDestFile = appTmpPath.getAbsolutePath() + File.separator + tempFilename;
Log.d("MainActivity", "tempDestFile : "+tempDestFile);
new MySpeech(speakTextTxt);

i've tested it on android emulator , and it works fine , but you need to specify the size of the sdCard of your emulator bye using device manager, edit eumlator, and specify the size of your sdcard : example 512 Mb. and then you will find the wav file in the path : mnt/sdcard/sounds/tmpaudio.wav to test it , just open the DDMS perspective, File Explorer, and then export the file to your PC .

Community
  • 1
  • 1
Houcine
  • 24,001
  • 13
  • 56
  • 83
  • @ When I try with the above code, I got the following error in the logcat, – Sekhar Bhetalam Feb 04 '13 at 10:15
  • This is the erro: 02-04 15:42:17.211: E/AndroidRuntime(5735): Uncaught handler: thread main exiting due to uncaught exception 02-04 15:42:17.351: E/AndroidRuntime(5735): java.lang.NullPointerException 02-04 15:42:17.351: E/AndroidRuntime(5735): at com.example.testmedai1.MainActivity$1.onClick(MainActivity.java:56) 02-04 15:42:17.351: E/AndroidRuntime(5735): at android.view.View.performClick(View.java:2418) – Sekhar Bhetalam Feb 04 '13 at 10:34
  • you have a `NullPointerException` at the line : *56* , what is the code in this line ? put the full code of the `onClick()` method – Houcine Feb 04 '13 at 10:46
  • That is actually my code problem. After that I resolved it and it is saying the file was saved. But I can't see the file in that folder. – Sekhar Bhetalam Feb 04 '13 at 10:52
  • enter to the `sdcard/` and you will find it under the name : `test.wav` – Houcine Feb 04 '13 at 10:54
  • Actullay I am debugging it by connecting my device to pc (I am using mac). I went to finder and checked for, but there is no file. Can you please help me how can I check for this? – Sekhar Bhetalam Feb 04 '13 at 10:58
  • you should check your device and not the finder in MAC, and not the pc , install the app Astro File Manager from google play in your device, and then go to the folder `/sdcard/` and then you will find your file `test.wav` – Houcine Feb 04 '13 at 11:01
  • You saved my life. It is stored there actually. But only problem is when I try to play that using realPlayer or MusicPlayer "Can not play the track. Unsupported file format". – Sekhar Bhetalam Feb 04 '13 at 11:21
  • I have a problem After all this, I found that my file size 0 kb. Can you please advice what is causing for this problem??? – Sekhar Bhetalam Feb 04 '13 at 11:32
  • try to install winamp app and try if it will play the wav file , otherwise, check the status of `mTts.synthesizeToFile(textToConvert, myHashRender, destinationFileName);`it returns an integer , if it returns `0` so the file is successfully saved, if it returns `-1` so there is an error , – Houcine Feb 04 '13 at 11:37
  • It was returning 0, But when I try to play it using winamp,MusicPlayer or Real player it saying that the file is is "unsupported format". And the size of the file is 0kb. – Sekhar Bhetalam Feb 04 '13 at 11:42
  • it's strange , i don't know why , and now i'm at work , when i go home i will try to develop a Demo for you to see what is exactly the error, and to save the time of redevelopping , plz upload your code on a server , and share the link with me . – Houcine Feb 04 '13 at 11:49
  • I have no chance to upload it on a server. Can you please sahre your emailid so that I can share you directly. Mine is sekhar.bethalam@gmail.com – Sekhar Bhetalam Feb 04 '13 at 12:12
  • hi its not workin as it is depricated now did have any idea here – Sunil Chaudhary Jun 18 '20 at 11:24
2

You can use synthesizeToFile()

From Android

HashMap<String, String> myHashRender = new HashMap();
String wakeUpText = "Are you up yet?";
String destFileName = "/sdcard/myAppCache/wakeUp.wav";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, wakeUpText);
mTts.synthesizeToFile(wakuUpText, myHashRender, destFileName);

Once you are notified of the synthesis completion, you can play the output file just like any other audio resource with android.media.MediaPlayer.

and for this you can use it

mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this,R.raw.button);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {                   
    @Override
    public void onCompletion(MediaPlayer mp) {
        mMediaPlayer.stop();
    }
});

now you are done

Usman Kurd
  • 7,212
  • 7
  • 57
  • 86