Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------- MainActivity.java --------------
- package com.example.texttospeech;
- import androidx.appcompat.app.AppCompatActivity;
- import android.annotation.SuppressLint;
- import android.app.Notification;
- import android.app.NotificationChannel;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.Intent;
- import android.graphics.Color;
- import android.graphics.drawable.Icon;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.EditText;
- import android.widget.Spinner;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class MainActivity extends AppCompatActivity {
- Context context;
- EditText userTextInput;
- private static final String BE_URL = "https://api.backendless.com/B2CF8D9A-B15E-4F50-85F4-76F683DAF9A4/ACDA2C94-94A8-4DC8-82F0-06409BFEC05E/services/GCP/textToSpeech";
- private String beUrl;
- String res, textToSpeech;
- // Notification parameters declaration
- NotificationManager notificationManager;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- setPointer();
- }
- private void setPointer() {
- this.context = this;
- res = "";
- textToSpeech = "Something went wrong";
- // Setting up the languages list
- final Spinner spinner = (Spinner)findViewById(R.id.lngSelector);
- // Create an array adapter using the string array and a default spinner layout
- ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item);
- // Specify the layout to use when the list of choices appears
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- // Apply the adapter to the spinner
- spinner.setAdapter(adapter);
- spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
- // Creating notification channel and passing it to the notification manager
- notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
- createNotificationChannel("com.example.texttospeech.news", "NotifyDemo Sound Url", "Text To Speech sound MP3");
- // Adding a listener to the button
- findViewById(R.id.btnRun).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- textToSpeech = ((EditText)findViewById(R.id.usrTxtInput)).getText().toString().trim().replace(" ", "%20");
- String language = String.valueOf(spinner.getSelectedItem());
- getSoundUrl(textToSpeech, getLangCode(language));
- // With Alert Dialog implementation
- AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
- alertBuilder.setMessage("Press the OK button to play the audio file").setTitle("Play sound file");
- alertBuilder.setPositiveButton("PLAY", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- Intent resultIntent = new Intent(context, ResultActivity.class);
- resultIntent.putExtra("resUrl", res);
- resultIntent.putExtra("resText", textToSpeech);
- startActivity(resultIntent);
- }
- });
- AlertDialog dialog = alertBuilder.create();
- dialog.show();
- }
- });
- }
- protected void createNotificationChannel(String id, String name, String description) {
- int importance = NotificationManager.IMPORTANCE_LOW;
- NotificationChannel channel = new NotificationChannel(id, name, importance);
- channel.setDescription(description);
- channel.enableLights(true);
- channel.setLightColor(Color.RED);
- channel.enableVibration(true);
- channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
- notificationManager.createNotificationChannel(channel);
- }
- protected void sendNotification() {
- int notificationID = 101;
- Intent resultIntent = new Intent(this, ResultActivity.class);
- resultIntent.putExtra("resUrl", res);
- resultIntent.putExtra("resText", textToSpeech);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- String channelID = "com.example.texttospeech.news";
- final Icon icon = Icon.createWithResource(MainActivity.this, android.R.drawable.ic_dialog_info);
- Notification.Action action = new Notification.Action.Builder(icon, "Play", pendingIntent).build();
- Notification notification = new Notification.Builder(MainActivity.this, channelID)
- .setContentTitle("Your MP3 file link")
- .setContentText("voice1.mp3")
- .setContentIntent(pendingIntent)
- .setActions(action)
- .setSmallIcon(android.R.drawable.ic_dialog_info).setChannelId(channelID).build();
- notificationManager.notify(notificationID, notification);
- }
- private String getLangCode(String language) {
- String lngCode = "en"; // Default language
- switch (language) {
- case "English":
- lngCode = "en";
- break;
- case "German":
- lngCode = "de";
- break;
- case "Spanish":
- lngCode = "es";
- break;
- case "Dutch":
- lngCode = "nl";
- break;
- case "French":
- lngCode = "fr";
- break;
- case "Arabic":
- lngCode = "ar";
- break;
- case "Hebrew":
- lngCode = "he";
- break;
- default:
- break;
- }
- return lngCode;
- }
- @SuppressLint("StaticFieldLeak")
- private void getSoundUrl(String textToSpeech, String language) {
- beUrl = BE_URL + "?text=" + textToSpeech + "&lang=" + language;
- new AsyncTask<String, Void, String>() {
- @Override
- protected String doInBackground(String... strings) {
- HttpURLConnection urlConnection = null;
- String result = "";
- try {
- URL url = new URL(beUrl);
- urlConnection = (HttpURLConnection)url.openConnection();
- int statusCode = urlConnection.getResponseCode();
- if(statusCode == 200) {
- InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
- String line;
- while((line = bufferedReader.readLine()) != null) {
- result += line;
- }
- inputStream.close();
- return result;
- } else {
- Log.e("Network Error", "doInBackground: The request responded with code " + statusCode);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- assert urlConnection != null;
- urlConnection.disconnect();
- }
- return result;
- }
- @Override
- protected void onPostExecute(String be_response) {
- res = be_response;
- sendNotification();
- }
- }.execute();
- }
- class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- }
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- }
- }
- //----------------- ResultActivity.java ---------------------
- package com.example.texttospeech;
- import androidx.appcompat.app.AppCompatActivity;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.TextView;
- import java.io.IOException;
- public class ResultActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_result);
- setPointer();
- }
- private void setPointer() {
- String audioUrl = getIntent().getStringExtra("resUrl");
- String text = getIntent().getStringExtra("resText");
- ((TextView)findViewById(R.id.txtLine)).setText(text.replace("%20", " "));
- playSound(audioUrl);
- }
- private void playSound(String myUrl) {
- final MediaPlayer mediaPlayer = new MediaPlayer();
- try {
- Log.e("myUrl", "playSound: " + myUrl.replace("\"", ""));
- mediaPlayer.setDataSource(myUrl.replace("\"", ""));
- mediaPlayer.prepareAsync();
- mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
- @Override
- public void onPrepared(MediaPlayer mp) {
- mp.start();
- }
- });
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- ////////////////////// XML Layouts ////////////////////
- //--------------- activity_main.xml -------------------
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <TextView
- android:id="@+id/textView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/title"
- android:textSize="30sp"
- android:textColor="@color/colorPrimary"
- android:textStyle="bold"
- android:gravity="center"
- android:layout_marginTop="80dp"/>
- <EditText
- android:id="@+id/usrTxtInput"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_weight="8"
- android:ems="10"
- android:inputType="textPersonName"
- android:layout_margin="30dp"
- android:text="@string/text_input_box" />
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_weight="10"
- android:layout_margin="30dp"
- android:gravity="center"
- android:orientation="horizontal">
- <TextView
- android:id="@+id/textView3"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:textSize="24sp"
- android:text="@string/choose_language"
- tools:ignore="NestedWeights" />
- <Spinner
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="3"
- android:id="@+id/lngSelector" />
- </LinearLayout>
- <Button
- android:layout_width="wrap_content"
- android:layout_marginBottom="60dp"
- android:padding="20sp"
- android:layout_gravity="center"
- android:layout_height="wrap_content"
- android:textSize="24sp"
- android:id="@+id/btnRun"
- android:text="@string/speak"
- style="@style/Widget.AppCompat.Button.Colored"/>
- </LinearLayout>
- </androidx.constraintlayout.widget.ConstraintLayout>
- //----------------- activity_result.xml -----------------
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".ResultActivity">
- <TextView
- android:id="@+id/txtLine"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center"
- android:text="Success"
- android:textSize="36sp"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- </androidx.constraintlayout.widget.ConstraintLayout>
- //------------------ strings.xml (from the values library) ------------
- <resources>
- <string name="app_name">Text To Speech</string>
- <string name="speak">Speak</string>
- <string name="choose_language">Choose a language</string>
- <string name="text_input_box">Put your text here...</string>
- <string name="title">Text To Speech App</string>
- <string-array name="languages">
- <item>English</item>
- <item>German</item>
- <item>Spanish</item>
- <item>Dutch</item>
- <item>French</item>
- <item>Arabic</item>
- <item>Hebrew</item>
- </string-array>
- </resources>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement