Advertisement
eranseg

Audio Notification

Jan 25th, 2020
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.21 KB | None | 0 0
  1. //---------- MainActivity.java --------------
  2.  
  3. package com.example.texttospeech;
  4.  
  5. import androidx.appcompat.app.AppCompatActivity;
  6.  
  7. import android.annotation.SuppressLint;
  8. import android.app.Notification;
  9. import android.app.NotificationChannel;
  10. import android.app.NotificationManager;
  11. import android.app.PendingIntent;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.graphics.Color;
  15. import android.graphics.drawable.Icon;
  16. import android.os.AsyncTask;
  17. import android.os.Bundle;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.widget.AdapterView;
  21. import android.widget.ArrayAdapter;
  22. import android.widget.EditText;
  23. import android.widget.Spinner;
  24.  
  25. import java.io.BufferedInputStream;
  26. import java.io.BufferedReader;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.net.HttpURLConnection;
  31. import java.net.URL;
  32.  
  33. public class MainActivity extends AppCompatActivity {
  34.  
  35.     Context context;
  36.     EditText userTextInput;
  37.     private static final String BE_URL = "https://api.backendless.com/B2CF8D9A-B15E-4F50-85F4-76F683DAF9A4/ACDA2C94-94A8-4DC8-82F0-06409BFEC05E/services/GCP/textToSpeech";
  38.     private String beUrl;
  39.     String res, textToSpeech;
  40.  
  41.     // Notification parameters declaration
  42.     NotificationManager notificationManager;
  43.  
  44.     @Override
  45.     protected void onCreate(Bundle savedInstanceState) {
  46.         super.onCreate(savedInstanceState);
  47.         setContentView(R.layout.activity_main);
  48.         setPointer();
  49.     }
  50.  
  51.     private void setPointer() {
  52.         this.context = this;
  53.         res = "";
  54.         textToSpeech = "Something went wrong";
  55.         // Setting up the languages list
  56.         final Spinner spinner = (Spinner)findViewById(R.id.lngSelector);
  57.         // Create an array adapter using the string array and a default spinner layout
  58.         ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item);
  59.         // Specify the layout to use when the list of choices appears
  60.         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  61.         // Apply the adapter to the spinner
  62.         spinner.setAdapter(adapter);
  63.         spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  64.  
  65.         // Creating notification channel and passing it to the notification manager
  66.         notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  67.         createNotificationChannel("com.example.texttospeech.news", "NotifyDemo Sound Url", "Text To Speech sound MP3");
  68.  
  69.         // Adding a listener to the button
  70.         findViewById(R.id.btnRun).setOnClickListener(new View.OnClickListener() {
  71.             @Override
  72.             public void onClick(View v) {
  73.                 textToSpeech = ((EditText)findViewById(R.id.usrTxtInput)).getText().toString().trim().replace(" ", "%20");
  74.                 String language = String.valueOf(spinner.getSelectedItem());
  75.                 getSoundUrl(textToSpeech, getLangCode(language));
  76.                 // With Alert Dialog implementation
  77.                 AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
  78.                 alertBuilder.setMessage("Press the OK button to play the audio file").setTitle("Play sound file");
  79.                 alertBuilder.setPositiveButton("PLAY", new DialogInterface.OnClickListener() {
  80.                     @Override
  81.                     public void onClick(DialogInterface dialog, int which) {
  82.                         Intent resultIntent = new Intent(context, ResultActivity.class);
  83.                         resultIntent.putExtra("resUrl", res);
  84.                         resultIntent.putExtra("resText", textToSpeech);
  85.                         startActivity(resultIntent);
  86.                     }
  87.                 });
  88.                 AlertDialog dialog = alertBuilder.create();
  89.                 dialog.show();
  90.             }
  91.         });
  92.     }
  93.  
  94.     protected void createNotificationChannel(String id, String name, String description) {
  95.         int importance = NotificationManager.IMPORTANCE_LOW;
  96.         NotificationChannel channel = new NotificationChannel(id, name, importance);
  97.         channel.setDescription(description);
  98.         channel.enableLights(true);
  99.         channel.setLightColor(Color.RED);
  100.         channel.enableVibration(true);
  101.         channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
  102.         notificationManager.createNotificationChannel(channel);
  103.     }
  104.  
  105.     protected void sendNotification() {
  106.         int notificationID = 101;
  107.         Intent resultIntent = new Intent(this, ResultActivity.class);
  108.         resultIntent.putExtra("resUrl", res);
  109.         resultIntent.putExtra("resText", textToSpeech);
  110.         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  111.         String channelID = "com.example.texttospeech.news";
  112.         final Icon icon = Icon.createWithResource(MainActivity.this, android.R.drawable.ic_dialog_info);
  113.         Notification.Action action = new Notification.Action.Builder(icon, "Play", pendingIntent).build();
  114.         Notification notification = new Notification.Builder(MainActivity.this, channelID)
  115.                 .setContentTitle("Your MP3 file link")
  116.                 .setContentText("voice1.mp3")
  117.                 .setContentIntent(pendingIntent)
  118.                 .setActions(action)
  119.                 .setSmallIcon(android.R.drawable.ic_dialog_info).setChannelId(channelID).build();
  120.         notificationManager.notify(notificationID, notification);
  121.     }
  122.  
  123.     private String getLangCode(String language) {
  124.         String lngCode = "en"; // Default language
  125.         switch (language) {
  126.             case "English":
  127.                 lngCode  = "en";
  128.                 break;
  129.             case "German":
  130.                 lngCode  = "de";
  131.                 break;
  132.             case "Spanish":
  133.                 lngCode  = "es";
  134.                 break;
  135.             case "Dutch":
  136.                 lngCode  = "nl";
  137.                 break;
  138.             case "French":
  139.                 lngCode  = "fr";
  140.                 break;
  141.             case "Arabic":
  142.                 lngCode  = "ar";
  143.                 break;
  144.             case "Hebrew":
  145.                 lngCode  = "he";
  146.                 break;
  147.             default:
  148.                 break;
  149.         }
  150.         return lngCode;
  151.     }
  152.  
  153.     @SuppressLint("StaticFieldLeak")
  154.     private void getSoundUrl(String textToSpeech, String language) {
  155.         beUrl = BE_URL + "?text=" + textToSpeech + "&lang=" + language;
  156.         new AsyncTask<String, Void, String>() {
  157.  
  158.             @Override
  159.             protected String doInBackground(String... strings) {
  160.                 HttpURLConnection urlConnection = null;
  161.                 String result = "";
  162.                 try {
  163.                     URL url = new URL(beUrl);
  164.                     urlConnection = (HttpURLConnection)url.openConnection();
  165.                     int statusCode = urlConnection.getResponseCode();
  166.                     if(statusCode == 200) {
  167.                         InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
  168.                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  169.                         String line;
  170.                         while((line = bufferedReader.readLine()) != null) {
  171.                             result += line;
  172.                         }
  173.                         inputStream.close();
  174.                         return result;
  175.                     } else {
  176.                         Log.e("Network Error", "doInBackground: The request responded with code " + statusCode);
  177.                     }
  178.                 } catch (IOException e) {
  179.                     e.printStackTrace();
  180.                 } finally {
  181.                     assert urlConnection != null;
  182.                     urlConnection.disconnect();
  183.                 }
  184.                 return result;
  185.             }
  186.            
  187.             @Override
  188.             protected void onPostExecute(String be_response) {
  189.                 res = be_response;
  190.                 sendNotification();
  191.             }
  192.         }.execute();
  193.     }
  194.  
  195.     class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
  196.  
  197.         @Override
  198.         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  199.  
  200.         }
  201.  
  202.         @Override
  203.         public void onNothingSelected(AdapterView<?> parent) {
  204.  
  205.         }
  206.     }
  207. }
  208.  
  209. //----------------- ResultActivity.java ---------------------
  210.  
  211. package com.example.texttospeech;
  212.  
  213. import androidx.appcompat.app.AppCompatActivity;
  214.  
  215. import android.content.Intent;
  216. import android.media.MediaPlayer;
  217. import android.os.Bundle;
  218. import android.util.Log;
  219. import android.widget.TextView;
  220.  
  221. import java.io.IOException;
  222.  
  223. public class ResultActivity extends AppCompatActivity {
  224.  
  225.     @Override
  226.     protected void onCreate(Bundle savedInstanceState) {
  227.         super.onCreate(savedInstanceState);
  228.         setContentView(R.layout.activity_result);
  229.         setPointer();
  230.     }
  231.  
  232.     private void setPointer() {
  233.         String audioUrl = getIntent().getStringExtra("resUrl");
  234.         String text = getIntent().getStringExtra("resText");
  235.         ((TextView)findViewById(R.id.txtLine)).setText(text.replace("%20", " "));
  236.         playSound(audioUrl);
  237.     }
  238.  
  239.     private void playSound(String myUrl) {
  240.         final MediaPlayer mediaPlayer = new MediaPlayer();
  241.         try {
  242.             Log.e("myUrl", "playSound: " + myUrl.replace("\"", ""));
  243.             mediaPlayer.setDataSource(myUrl.replace("\"", ""));
  244.             mediaPlayer.prepareAsync();
  245.             mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  246.                 @Override
  247.                 public void onPrepared(MediaPlayer mp) {
  248.                     mp.start();
  249.                 }
  250.             });
  251.         } catch (IOException e) {
  252.             e.printStackTrace();
  253.         }
  254.     }
  255. }
  256.  
  257. ////////////////////// XML Layouts ////////////////////
  258. //--------------- activity_main.xml -------------------
  259.  
  260. <?xml version="1.0" encoding="utf-8"?>
  261. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  262.     xmlns:app="http://schemas.android.com/apk/res-auto"
  263.     xmlns:tools="http://schemas.android.com/tools"
  264.     android:layout_width="match_parent"
  265.     android:layout_height="match_parent"
  266.     tools:context=".MainActivity">
  267.  
  268.     <LinearLayout
  269.         android:layout_width="match_parent"
  270.         android:layout_height="match_parent"
  271.         android:orientation="vertical">
  272.  
  273.         <TextView
  274.             android:id="@+id/textView"
  275.             android:layout_width="match_parent"
  276.             android:layout_height="wrap_content"
  277.             android:text="@string/title"
  278.             android:textSize="30sp"
  279.             android:textColor="@color/colorPrimary"
  280.             android:textStyle="bold"
  281.             android:gravity="center"
  282.             android:layout_marginTop="80dp"/>
  283.  
  284.         <EditText
  285.             android:id="@+id/usrTxtInput"
  286.             android:layout_width="match_parent"
  287.             android:layout_height="match_parent"
  288.             android:layout_weight="8"
  289.             android:ems="10"
  290.             android:inputType="textPersonName"
  291.             android:layout_margin="30dp"
  292.             android:text="@string/text_input_box" />
  293.  
  294.         <LinearLayout
  295.             android:layout_width="match_parent"
  296.             android:layout_height="match_parent"
  297.             android:layout_weight="10"
  298.             android:layout_margin="30dp"
  299.             android:gravity="center"
  300.             android:orientation="horizontal">
  301.  
  302.             <TextView
  303.                 android:id="@+id/textView3"
  304.                 android:layout_width="match_parent"
  305.                 android:layout_height="wrap_content"
  306.                 android:layout_weight="2"
  307.                 android:textSize="24sp"
  308.                 android:text="@string/choose_language"
  309.                 tools:ignore="NestedWeights" />
  310.             <Spinner
  311.                 android:layout_width="match_parent"
  312.                 android:layout_height="wrap_content"
  313.                 android:layout_weight="3"
  314.                 android:id="@+id/lngSelector" />
  315.         </LinearLayout>
  316.         <Button
  317.             android:layout_width="wrap_content"
  318.             android:layout_marginBottom="60dp"
  319.             android:padding="20sp"
  320.             android:layout_gravity="center"
  321.             android:layout_height="wrap_content"
  322.             android:textSize="24sp"
  323.             android:id="@+id/btnRun"
  324.             android:text="@string/speak"
  325.             style="@style/Widget.AppCompat.Button.Colored"/>
  326.  
  327.     </LinearLayout>
  328. </androidx.constraintlayout.widget.ConstraintLayout>
  329.  
  330. //----------------- activity_result.xml -----------------
  331.  
  332. <?xml version="1.0" encoding="utf-8"?>
  333. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  334.     xmlns:app="http://schemas.android.com/apk/res-auto"
  335.     xmlns:tools="http://schemas.android.com/tools"
  336.     android:layout_width="match_parent"
  337.     android:layout_height="match_parent"
  338.     tools:context=".ResultActivity">
  339.  
  340.     <TextView
  341.         android:id="@+id/txtLine"
  342.         android:layout_width="match_parent"
  343.         android:layout_height="match_parent"
  344.         android:gravity="center"
  345.         android:text="Success"
  346.         android:textSize="36sp"
  347.         app:layout_constraintStart_toStartOf="parent"
  348.         app:layout_constraintTop_toTopOf="parent" />
  349. </androidx.constraintlayout.widget.ConstraintLayout>
  350.  
  351. //------------------ strings.xml (from the values library) ------------
  352.  
  353. <resources>
  354.     <string name="app_name">Text To Speech</string>
  355.     <string name="speak">Speak</string>
  356.     <string name="choose_language">Choose a language</string>
  357.     <string name="text_input_box">Put your text here...</string>
  358.     <string name="title">Text To Speech App</string>
  359.     <string-array name="languages">
  360.         <item>English</item>
  361.         <item>German</item>
  362.         <item>Spanish</item>
  363.         <item>Dutch</item>
  364.         <item>French</item>
  365.         <item>Arabic</item>
  366.         <item>Hebrew</item>
  367.     </string-array>
  368. </resources>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement