Implement Voice input mechanism in android

Google Now made us lazy. it can make call for you , can set alarm or reminder for you and much more things that you and i even don't know. And it is without using key board or even without touching your smart phone. as it provide voice input, it is one of the best functionality smart phone provides. Apps and User preference changes day by day and still you provide input using key board i think you have to rethink before your app next update.
Voice input is supported form android  v 2.3 Ginger bread so you can implement it in your application without using any third party Api. you can implement it using RecognizerIntent.ACTION_RECOGNIZE_SPEECH intent. In this tutorial i am going to show you how you can implement it in your app. just go through full tutorial i am sure you will implement it successfully.

Step -1
Create New Android application and give name to it. in this tutorial it is VoiceInputDemo.java
  • minSdkVersion="11”
  • targetSdkVersion="22"
  • (code updated)

you can use below android version also for compilation and build option (As per requirement). now put below code in your project activity_voiceinput_demo.xml file. you can set layout as you want but for practice purpose you can go with same.

activity_voiceinput_demo.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize"
    tools:context="com.androprogrammer.tutorials.samples.VoiceInputDemo">

    <LinearLayout
        android:id="@+id/layout_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="@android:drawable/dialog_holo_light_frame"
        android:padding="9dp">

        <EditText
            android:id="@+id/et_word"
            android:layout_width="0dip"
            android:layout_weight="0.8"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|top"
            android:background="@drawable/searchedittext"
            android:gravity="start"
            android:hint="Search..."
            android:padding="8dp"
            android:singleLine="true"
            android:textSize="15sp"/>
        
        <ImageButton
            android:id="@+id/ib_speak"
            style="android: attr/borderlessButtonStyle;"
            android:layout_width="0dip"
            android:layout_weight="0.1"
            android:layout_height="32dp"
            android:contentDescription="Search"
            android:background="@android:color/transparent"
            android:layout_gravity="right|center_vertical"
            android:src="@android:drawable/ic_btn_speak_now"/>
    </LinearLayout>

</RelativeLayout>


I have given style to the Edit text so it looks nice. below xml file is style applied on it . so now create one resource file and put this code in it.
edittextstyle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#FFFFFF"/>
    <padding android:left="10dp"/>
    <corners android:radius="1dip"/>

</shape>

Step -2 
Layout is set for your activity. now put below code inside your main class file or where you want voice input. the RecognizerIntent Class allows you to use inbuilt speech recolonization functionality. As i have used this class (intent) it will allow to prompt a dialog box where you can display message what ever you want.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
After user input you can get the result using onActivityResult() method. i get that response and set it into the edit text. now put the below code in class file.
VoiceInputDemo.java

package com.androprogrammer.tutorials.samples;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.transition.Explode;
import android.transition.Transition;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;

import com.androprogrammer.tutorials.R;
import com.androprogrammer.tutorials.activities.Baseactivity;
import com.androprogrammer.tutorials.util.Common;

import java.util.ArrayList;
import java.util.List;

public class VoiceInputDemo extends Baseactivity {

    protected View view;
    private EditText word;
    private ImageButton bt_voiceinput;
    private static final int REQUEST_CODE = 1234;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);

            //set the transition
            Transition ts = new Explode();
            ts.setDuration(5000);
            getWindow().setEnterTransition(ts);
            getWindow().setExitTransition(ts);
        }

        super.onCreate(savedInstanceState);
        setReference();

        setToolbarElevation(7);

        setToolbarSubTittle(this.getClass().getSimpleName());

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            bt_voiceinput.setEnabled(false);
        }

        bt_voiceinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startVoiceRecognitionActivity();
            }
        });
        word.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                bt_voiceinput.setEnabled(false);
            }
        });

    }

    @Override
    public void setReference() {

        view = LayoutInflater.from(this).inflate(R.layout.activity_voiceinput_demo,container);
        bt_voiceinput = (ImageButton) view.findViewById(R.id.ib_speak);
        word = (EditText) view.findViewById(R.id.et_word);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                finish();
                // NavUtils.navigateUpFromSameTask(this);
                // return true;
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //If Voice recognition is successful then it returns RESULT_OK
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    String Query = textMatchList.get(0);
                    word.setText(Query);
                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                Common.showToast(this, "Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                Common.showToast(this, "No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                Common.showToast(this, "Server Error");
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}



Screen Shots

So that's it from coding side now you can run app and test it. i hope you it will run smoothly.if you have any query comment it in below comment box.
Keep coding...

2 comments :

  1. import com.androprogrammer.tutorials.R;
    import com.androprogrammer.tutorials.activities.Baseactivity;
    import com.androprogrammer.tutorials.util.Common;

    what are those ?

    ReplyDelete
    Replies
    1. Hey islam,
      Those are the common class of my tutorial app.
      you can check out my git for code.
      https://github.com/WasimMemon/Myapplications/tree/master/Tutorials

      Delete