I'm new to programming, and I'm creating an app with texttospeech and I wanna be able to share the tts output as an audio file to other apps like whatsapp for example. I have heard about synthesizetofile() but I don't know anything about it. Here's my code:
Main Activity class
package com.example.texttospeech;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
EditText etInput;
Button btDone, btShare;
MediaPlayer mMediaPlayer;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etInput = findViewById(R.id.et_input);
btDone = findViewById(R.id.bt_done);
btShare = findViewById(R.id.btn_share);
textToSpeech = new TextToSpeech(getApplicationContext()
, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int lang = textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
btDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String s = etInput.getText().toString();
//int speech = textToSpeech.speak(s, TextToSpeech.QUEUE_FLUSH, null);
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "speak");
File myDir = getApplicationContext().getFilesDir();
String documents = "documents/data";
File documentsFolder = new File(myDir, documents);
documentsFolder.mkdir();
String path = "/"+documents+"/"+"test.mp3";
textToSpeech.synthesizeToFile("text to speech to audio", map, path);
mMediaPlayer = new MediaPlayer();
try{
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
}
catch (Exception e) {
Log.d("ROYs", e.toString());
e.printStackTrace();
}
mMediaPlayer.start();
}
});
btShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
Intent intent = new Intent( Intent.ACTION_SEND );
intent.setType("audio/mp3");
startActivity( intent );
}
});
}
private void shareAudio()
{
Bundle bundle = new Bundle();
Intent intent = new Intent( Intent.ACTION_SEND );
intent.setType("audio/mp3");
startActivity( intent );
}
}
Anyone who helps, would be appreciated very much!