Skip to content
Related Articles

Related Articles

Improve Article

Add OnTouchListener to ImageView to Perform Speech to Text in Android

  • Last Updated : 31 Mar, 2021

Speech to text is a feature that generally means that anything that the user says is converted into text. This feature has come out to be a very common and useful feature for the users. In various places where search feature is implemented like Google Search also in apps like google keyboard, etc because it gives users a great experience. So, in this article, we are going to implement Speech to text by using OnTouchListener of ImageView and store the input text in EditText.

What we are going to build in this article?

In this article, we will develop a sample application with an ImageView of a microphone and an EditText in its MainActivity and by using the  OnTouchListener of ImageView we will give input to EditText in the form of Speech to Text. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file



Now, go-to the app >res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <!--EditText to show the the recorded text-->
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="52dp"
        android:layout_margin="12dp"
        android:layout_marginTop="600dp"
        android:hint="Enter here"
        android:textColor="#0F9D58" />
    
    <!--ImageView to use as a button-->
    <ImageView
        android:id="@+id/microphone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="400dp"
        app:srcCompat="@drawable/microphone" />
    
</LinearLayout>

Step 3: Working with the MainActivity.java file

Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Locale;
  
public class MainActivity extends AppCompatActivity {
  
    // declare editText
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // definition of editText using method findViewById()
        editText = findViewById(R.id.edit_text);
          
        // initializing mSpeechRecognizer using SpeechRecognizer class
        final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
          
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
          
        // various methods of RecognitionListener class
        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {
  
            }
  
            @Override
            public void onBeginningOfSpeech() {
  
            }
  
            @Override
            public void onRmsChanged(float v) {
  
            }
  
            @Override
            public void onBufferReceived(byte[] bytes) {
  
            }
  
            @Override
            public void onEndOfSpeech() {
  
            }
  
            @Override
            public void onError(int i) {
  
            }
  
            @Override
            public void onResults(Bundle bundle) {
                  
                // getting all the matches
                ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
  
                // displaying the first match
                if (matches != null)
                    editText.setText(matches.get(0));
            }
  
            @Override
            public void onPartialResults(Bundle bundle) {
  
            }
  
            @Override
            public void onEvent(int i, Bundle bundle) {
  
            }
        });
          
        // set OnTouchListener to imageView named microphone
        findViewById(R.id.microphone).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                      
                    // case MotionEvent.ACTION_UP run when user will remove
                    // his/her finger from microphone imageView
                    case MotionEvent.ACTION_UP:
                          
                        mSpeechRecognizer.stopListening();
                        editText.setHint(" ");
                        break;
  
                    // case MotionEvent.ACTION_UP run when user will put his/her
                    // finger from microphone imageView
                    case MotionEvent.ACTION_DOWN:
                          
                        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                        editText.setText("");
                        editText.setHint("");
                        break;
                }
                return false;
            }
        });
    }
}

Step 4: Working with the AndroidManifest.xml file

Finally, go to the app > manifests > AndroidManifest.xml file and add the below-written permission there.

XML




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

 That’s all, now the application is ready to install on the device. Here is what the output of the application looks like.

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :