离线语音识别机器人采取不必要的声音离线、机器人、不必要、语音识别

由网友(最美的詮釋?簡單)分享简介:我已经做了很多的研究,并试图离线口袋狮身人面像,但它正在周围的声音也正在和我的应用程序不同的反应。是否有上述奇巧4.4的谷歌离线应用程序..我从2周尝试。感谢您的宝贵答案。详细信息:当活动开始第一文本有后完成,阅读语音识别必须采取的声音,并为每个命令前阅读的内容(文本语音转换):(接下来,previous,前进,选项,...

我已经做了很多的研究,并试图离线口袋狮身人面像,但它正在周围的声音也正在和我的应用程序不同的反应。是否有上述奇巧4.4的谷歌离线应用程序..我从2周尝试。感谢您的宝贵答案。

详细信息:当活动开始第一文本有后完成,阅读语音识别必须采取的声音,并为每个命令前阅读的内容(文本语音转换):(接下来,previous,前进,选项,1,2,3,4等)。根据命令,它具有识别和onresult方法应对。

错误:我采取了一些声音后,得到错误

  06-18 19:54:00.159:V / onBeginningOfSpeech(3360):onBeginningOfSpeech
06-18 19:54:01.024:V / onPartialResult(3360):选项
06-18 19:54:01.109:I / cmusphinx(3360):信息:fsg_search.c(843):105帧,5333隐马尔可夫模型(50 / FR),7748句音(73 / FR),371历史条目(3 / FR)
06-18 19:54:01.110:I / SpeechRecognizer(3360):终止确认
06-18 19:54:01.110:E / cmusphinx(3360):错误:fsg_​​search.c,行913:最终结果不语法匹配帧105
06-18 19:54:01.111:V / onPartialResult  - >(3360):选项
06-18 19:54:01.111:V / onResult(3360):onResult
 

的Andr​​oid蜂巢离线链接

但是,如果我关掉互联网是没有脱机工作。

在pocketsphinx它不反应来校正字。如果我说下一个是附近采用由另一个附加的钥匙的声音内容,它给了我很大的问题。是否有任何解决方案或库脱机使用。所有脱机离线谷歌语音支持。

下面是我的code是什么尝试

包com.example.sample1; 引入静态edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup; 进口的java.io.File; 进口java.io.IOException异常; 进口的java.util.ArrayList; 进口的java.util.HashMap; 进口java.util.Locale中; 进口edu.cmu.pocketsphinx.RecognitionListener; 进口android.app.Activity; 进口android.graphics.Color; 进口android.os.AsyncTask; 进口android.os.Bundle; 进口android.os.Handler; 进口android.speech.tts.TextToSpeech; 进口android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; 进口android.util.Log; 进口android.view.View; 进口android.view.View.OnClickListener; 进口android.widget.Button; 进口android.widget.ExpandableListView; 进口android.widget.ExpandableListView.OnChildClickListener; 进口android.widget.ExpandableListView.OnGroupClickListener; 进口android.widget.ExpandableListView.OnGroupExpandListener; 进口android.widget.TextView; 进口android.widget.Toast; 进口edu.cmu.pocketsphinx.Assets; 进口edu.cmu.pocketsphinx.Hypothesis; 进口edu.cmu.pocketsphinx.SpeechRecognizer; 公共类萨姆扩展活动实现RecognitionListener,TextToSpeech.OnInitListener {     / *命名搜索允许快速重新配置去codeR * /     私有静态最后弦乐DIGITS_SEARCH =数字;     私人SpeechRecognizer识别器;     私人的HashMap<字符串,整数>字幕;     私人TextView的caption_text;     私人TextView的result_text;     ArrayList的<字符串> RESULT1;     私人按钮buttonLeft;     私人按钮buttonRight;     诠释计数= 0;     私人的ArrayList< D​​ataAnswer> dummyListTemp;     私人的ArrayList< D​​ataAnswer> dummyList;     AnswerDataAdapter listAdapter = NULL;     INT conteo = 0;     处理程序=新的处理程序();     私人TextToSpeech TTS;     字符串readIt =;     HashMap的<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();     @覆盖     公共无效的onCreate(包状态){         super.onCreate(州);         Log.v(的onCreate,的onCreate);         // prepare的UI数据         标题=新的HashMap<字符串,整数>();         captions.put(DIGITS_SEARCH,R.string.digits_caption);         的setContentView(R.layout.quiz);         caption_text =(TextView中)findViewById(R.id.caption_text);         result_text =(TextView中)findViewById(R.id.result_text);     // listViewAnswer =(ExpandableListView)findViewById(R.id.listViewAnswer);         buttonRight =(按钮)findViewById(R.id.buttonRight);         buttonLeft =(按钮)findViewById(R.id.buttonLeft);         result_text.setText(结果---计算值:);         TTS =新TextToSpeech(这一点,这一点);         params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_IDstringId);         字符串文字=世界充满的chanllenge的;         //斯皮克斯文本,然后再经过完井阅读文本语音recoginzation必须启动         SPEAKOUT(文本);         buttonRight.setOnClickListener(新OnClickListener(){             @覆盖             公共无效的onClick(视图v){                 尝试 {                     // onClickRight();                     Toast.makeText(getApplicationContext(),右,Toast.LENGTH_SHORT).show();                 }赶上(例外五){                     e.printStackTrace();                 }             }         });         buttonLeft.setOnClickListener(新OnClickListener(){             @覆盖             公共无效的onClick(视图v){                 // onClickLeft();                 Toast.makeText(getApplicationContext(),左,Toast.LENGTH_SHORT).show();             }         });         //识别初始化一个耗时,它涉及的IO,         //所以我们在异步任务执行它         //如果(!tts.isSpeaking()){         新的AsyncTask<虚空,虚空,异常>(){             @覆盖             保护异常doInBackground(空... PARAMS){                 尝试 {                     资产的资产=新资产(Sam.this);                     文件assetDir = assets.syncAssets();                     Log.v(AsyncTask的,AsyncTask的);                     SETU precognizer(assetDir);                 }赶上(IOException异常E){                     返回e的;                 }                 返回null;             }             @覆盖             保护无效onPostExecute(异常的结果){                 Log.v(onPostExecute,onPostExecute);                 尝试{                     如果(结果!= NULL){                         //caption_text.setText("Failed给init识别+结果);                         Toast.makeText(getApplicationContext(),无法初始化识别器,Toast.LENGTH_SHORT).show();                     } 其他 {                         FireRecognition();                         // switchSearch(DIGITS_SEARCH);                     }                 }赶上(例外五){                     e.printStackTrace();                 }             }         }。执行();     }     @覆盖     公共无效的onDestroy(){         super.onDestroy();         Log.v(的onDestroy,的onDestroy);         recognizer.cancel();         recognizer.shutdown();         如果(TTS!= NULL){             tts.stop();             tts.shutdown();         }     }     公共无效FireRecognition(){         Log.d(承认,识别入门);         //caption_text.setText("Recognition开始)!;         //Toast.makeText(getApplicationContext(),承认就开始吧!,Toast.LENGTH_SHORT).show();         recognizer.stop();         //recognizer.startListening("digits);     }     / **      *在部分结果,我们得到关于当前的假设快速更新。在      *关键词识别模式中,我们可以在这里做出反应,在其它模式下,我们需要等待      *对于最终结果的onResult。      * /     @覆盖     公共无效onPartialResult(假设假设){         尝试 {             //Log.v("onPartialResult,onPartialResult);             如果(假设== NULL)                 返回;             Log.v(onPartialResult,hypothesis.getHypstr()的toString());             字符串文本= hypothesis.getHypstr();             如果(识别器!= NULL)                 recognizer.stop();             caption_text.setText(部分结果 - 计算值:+文字);             Log.v(onPartialResult - >中,文本);             // Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();         }赶上(例外五){             e.printStackTrace();         }     }     / **      *当我们停止识别此回调被调用。      * /     @覆盖     公共无效onResult(假设假设){         尝试{             Log.v(onResult,onResult);             // result_text.setText();             如果(假设!= NULL){                 字符串文本= hypothesis.getHypstr();                 //Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 //((TextView中)findViewById(R.id.result_text))的setText(文本)。                 如果(text.toLowerCase()。等于(下一步)){                     result_text.setText(结果---计算值:+文字);                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 }否则,如果(text.toLowerCase()。等于(previous)){                     result_text.setText(结果---计算值:+文字);                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 }否则,如果(text.toLowerCase()。修剪()。等于(方案一.toLowerCase()。修剪())){                     result_text.setText(结果---计算值:+文字);                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                     result_text.setText(结果---计算值:+文字);                 }否则,如果(text.toLowerCase()。修剪()。等于(选项二.toLowerCase()的toString())){                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 }否则,如果(text.toLowerCase()。修剪()。等于(选项三.toLowerCase()的toString())){                     result_text.setText(结果---计算值:+文字);                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 }否则,如果(text.toLowerCase()。修剪()。等于(选项四.toLowerCase()的toString())){                     result_text.setText(结果---计算值:+文字);                     Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();                 } 其他 {                     Toast.makeText(getApplicationContext(),禁止访问: - +文字,Toast.LENGTH_SHORT).show();                 }                 Log.v(onResult - >中,文本);                 如果(识别器!= NULL)                     recognizer.startListening(数字);             }         }赶上(例外五){             e.printStackTrace();         }     }     @覆盖     公共无效onBeginningOfSpeech(){         Log.v(onBeginningOfSpeech,onBeginningOfSpeech);     }     / **      *我们停下识别器在这里得到一个最终结果      * /     @覆盖     公共无效onEndOfSpeech(){         Log.v(onEndOfSpeech,onEndOfSpeech);         如果(!recognizer.getSearchName()。等于(DIGITS_SEARCH))             switchSearch(DIGITS_SEARCH);     }     私人无效switchSearch(字符串searchName){         Log.v(switchSearch,switchSearch --->中+ searchName);         recognizer.stop();         //如果我们不察觉,下手超时听(10000毫秒或10秒)。         如果(searchName.equals(DIGITS_SEARCH))             recognizer.startListening(searchName,10000);         /* 其他             recognizer.startListening(searchName,10000); * /         / *字符串标题= getResources()的getString(captions.get(searchName))。         caption_text.setText(字幕); * /     }     私人无效SETU precognizer(文件assetsDir)抛出IOException异常{         //识别器可以被配置成执行多个搜索         //不同的种类和交换机之间的         Log.v(SETU precognizer,SETU precognizer);         识别= defaultSetup()                 .setAcousticModel(新文件(assetsDir,EN-US-PTM))                 .setDictionary(新文件(assetsDir,cmudict烯us.dict))                 //禁用原始音频注释出这个电话的记录(需要很大的空间,在设备上)                 .setRawLogDir(assetsDir)                 //阈值调整为关键词的误报和遗漏之间的平衡                 .setKeywordThreshold(1E-20F)// 1E-20F 1E-45F                 //使用上下文无关的拼音搜索,上下文相关的是移动速度太慢                 // .setBoolean( - allphone_ci,真)                 .getRecognizer();         recognizer.addListener(本);         / **在你的应用程序,你可能不需要添加所有这些搜索。          *他们被添加在这里展示。你可以离开只是一个。          * /         //创建关键字激活搜索。         // recognizer.addKeyphraseSearch(KWS_SEARCH,关键词短语);         //创建基于语法的搜索数字识别         文件digitsGrammar =新的文件(assetsDir,digits.gram);         recognizer.addGrammarSearch(DIGITS_SEARCH,digitsGrammar);     }     @覆盖     公共无效onerror的(异常错误){         Log.v(onError的,onError的);         //caption_text.setText(error.getMessage());         Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_SHORT).show();     }     @覆盖     公共无效onTimeout(){         Log.v(onTimeout,onTimeout);         switchSearch(DIGITS_SEARCH);     }     @燮pressWarnings(德precation)     @覆盖     公共无效的OnInit(INT状态){         tts.setOnUtteranceCompletedListener(新OnUtteranceCompletedListener(){             @覆盖             公共无效onUtteranceCompleted(字符串utteranceId){                 runOnUiThread(新的Runnable(){                     @覆盖                     公共无效的run(){                         如果(识别器!= NULL)                             recognizer.startListening(数字);                         //Toast.makeText(getApplicationContext(),已完成,Toast.LENGTH_LONG).show();                     }                 });             }         });         如果(状态== TextToSpeech.SUCCESS){             INT结果= tts.setLanguage(Locale.US);             Log.i(成功,已完成);             如果(结果== TextToSpeech.LANG_MISSING_DATA ||结果== TextToSpeech.LANG_NOT_SUPPORTED){                 Log.e(TTS,这个语言不支持);             } 其他 {                 //buttonSpeak.setEnabled(true);                 // 讲出();                 字符串文本=没有发现声音的ToString();                 Log.i(其他,其他);                 // SPEAKOUT(文本);             }         } 其他 {             Log.e(TTS,动初始化失败!);         }     }     @燮pressWarnings(德precation)     私人无效SPEAKOUT(字符串文本){         如果(tts.isSpeaking()){             //recognizer.stop();         }         //字符串文本=((TextView中)findViewById(R.id.caption_text))的getText()的toString()。         tts.speak(文字,TextToSpeech.QUEUE_FLUSH,则params);         Log.i(说起 - >中,****+ tts.isSpeaking());     } } 这款智能机器人,它实现讲故事 实时对讲

而在digit.gram

  #JSGF V1.0;

语法数字;

<数字> =方案一|
          方案二|
          方案三|
          选项​​4 |
          返回|
          previous |
          下一个;

公共和LT;数字> =<数字> +;
 

以上是我的code。如果它的任何一个工作,请让我知道解决的办法 这里是我的XML quiz.xml

< XML版本=1.0编码=UTF-8&GT?; < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android     机器人:layout_width =match_parent     机器人:layout_height =match_parent     机器人:方向=垂直>     <的LinearLayout         机器人:ID =@ + ID / linearLayout2         机器人:layout_width =match_parent         机器人:layout_height =WRAP_CONTENT         机器人:layout_alignParentLeft =真         机器人:layout_below =@ + ID / linearLayout1         机器人:方向=垂直>         < ExpandableListView             机器人:ID =@ + ID / listViewAnswer             机器人:layout_width =match_parent             机器人:layout_height =301dp             机器人:可聚焦=假             机器人:focusableInTouchMode =假             机器人:childDivider =#334455>         < / ExpandableListView>     < / LinearLayout中>     < RelativeLayout的         机器人:ID =@ + ID / relativeLayout1         机器人:layout_width =match_parent         机器人:layout_height =WRAP_CONTENT         机器人:layout_alignParentLeft =真         机器人:layout_below =@ + ID / linearLayout2         机器人:layout_marginTop =10dip         机器人:方向=横向>         <按钮             机器人:ID =@ + ID / buttonRight             机器人:layout_width =WRAP_CONTENT             机器人:layout_height =WRAP_CONTENT             机器人:layout_alignParentRight =真             机器人:layout_marginRight =10dip             机器人:文本=下一步/>         <按钮             机器人:ID =@ + ID / buttonLeft             机器人:layout_width =WRAP_CONTENT             机器人:layout_height =WRAP_CONTENT             机器人:layout_marginLeft =10dip             机器人:文本=previous/>     < / RelativeLayout的>     < RelativeLayout的         机器人:ID =@ + ID / relativeLayout2         机器人:layout_width =match_parent         机器人:layout_height =WRAP_CONTENT         机器人:layout_alignParentLeft =真         机器人:layout_below =@ + ID / relativeLayout1>         <的TextView             机器人:ID =@ + ID / result_text             机器人:layout_width =match_parent             机器人:layout_height =WRAP_CONTENT             机器人:layout_alignParentLeft =真             机器人:textAppearance =机器人:ATTR / textAppearanceMedium             机器人:文字颜色=#556677/>         <的TextView             机器人:ID =@ + ID / caption_text             机器人:layout_width =match_parent             机器人:layout_height =WRAP_CONTENT             机器人:layout_below =@ + ID / result_text             机器人:layout_alignParentLeft =真             机器人:文字颜色=#443399/>     < / RelativeLayout的> < / RelativeLayout的>

更新:

如果u使用的 addKeywordSearch

 文件digitsGrammar =新的文件(context.getFilesDir(),digits.gram);
recognizer.addKeywordSearch(DIGITS_SEARCH,digitsGrammar);
 

然后digit.gram只写

 方案一/ 1E-1 /
 选项​​二/ 1E-1 /
 第三个选项/ 1E-1 /
 选项​​4 / 1E-1 /
 回/ 1E-1 /
 previous / 1E-1 /
 接下来/ 1E-1 /
 

如果您使用的是 addGrammarSearch

 文件digitsGrammar =新的文件(context.getFilesDir(),digits.gram);
 recognizer.addGrammarSearch(DIGITS_SEARCH,digitsGrammar);
 

然后digit.gram

  #JSGF V1.0;

语法数字;

<数字> =方案一|
      方案二|
      方案三|
      选项​​4 |
      返回|
      previous |
      下一个;

     公共和LT;数字> =<数字> +;
 

解决方案

您需要使用的,而不是语法模式,连续收听关键词识别模式

您可以在这里找到例如:

Recognizing使用PocketSphinx 多个关键字

I have did a lot for research and tried offline pocket sphinx but it is taking surrounding voice it is taking and reacting my app differently. Is there any Google offline app for above kitkat 4.4.. i am trying it from 2 week. Thank for your valuable answer.

Details: When the activity starts first text has to read the content (Text to speech) after it complete, reading voice recognition has to take voice and as per command ex: (next, previous, forward, option, 1, 2, 3, 4 etc). As per command it has to recognize and react to it in onresult method.

Error: i am getting error after taking some voice

06-18 19:54:00.159: V/onBeginningOfSpeech(3360): onBeginningOfSpeech
06-18 19:54:01.024: V/onPartialResult(3360): option
06-18 19:54:01.109: I/cmusphinx(3360): INFO: fsg_search.c(843): 105 frames, 5333 HMMs (50/fr), 7748 senones (73/fr), 371 history entries (3/fr)
06-18 19:54:01.110: I/SpeechRecognizer(3360): Stop recognition
06-18 19:54:01.110: E/cmusphinx(3360): ERROR: "fsg_search.c", line 913: Final result does not match the grammar in frame 105
06-18 19:54:01.111: V/onPartialResult-->(3360): option
06-18 19:54:01.111: V/onResult(3360): onResult

Android Hive offline link

But if I turn off internet it is not working offline.

In pocketsphinx it is not reacting to correct word. If I say "next" it takes near by voice content of another appends the "key" and it gives me lot of problem. Is there any solution or library to use offline. Any offline google offline voice support.

Below is my code what is tried

package com.example.sample1;

import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import edu.cmu.pocketsphinx.RecognitionListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.SpeechRecognizer;

public class Sam extends Activity implements RecognitionListener, TextToSpeech.OnInitListener {

    /* Named searches allow to quickly reconfigure the decoder */

    private static final String DIGITS_SEARCH = "digits";

    private SpeechRecognizer recognizer;
    private HashMap<String, Integer> captions;
    private TextView caption_text;
    private TextView result_text;
    ArrayList<String> result1;
    private Button buttonLeft;
    private Button buttonRight;
    int count = 0;
    private ArrayList<DataAnswer> dummyListTemp;
    private ArrayList<DataAnswer> dummyList;
    AnswerDataAdapter listAdapter = null;
    int conteo = 0;
    Handler a = new Handler();
    private TextToSpeech tts; 
    String readIt ="";

    HashMap<String, String> params = new HashMap<String, String>();

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        Log.v("onCreate", "onCreate");

        // Prepare the data for UI
        captions = new HashMap<String, Integer>();

        captions.put(DIGITS_SEARCH, R.string.digits_caption);

        setContentView(R.layout.quiz);
        caption_text = (TextView) findViewById(R.id.caption_text);
        result_text = (TextView) findViewById(R.id.result_text);
    //  listViewAnswer = (ExpandableListView) findViewById(R.id.listViewAnswer);
        buttonRight  = (Button) findViewById(R.id.buttonRight);
        buttonLeft  = (Button) findViewById(R.id.buttonLeft);
        result_text.setText("Result --->: ");

        tts = new TextToSpeech(this, this);  

        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");

        String text = "World is full of chanllenge"; 
        //Speakes the text first and then after comple reading text voice recoginzation must start
        speakOut(text);




        buttonRight.setOnClickListener(new OnClickListener() {          
            @Override
            public void onClick(View v) {
                try {
                    //onClickRight();

                    Toast.makeText(getApplicationContext(), "Right", Toast.LENGTH_SHORT).show();
                } catch (Exception e){
                    e.printStackTrace();
                }


            }
        });

        buttonLeft.setOnClickListener(new OnClickListener() {           
            @Override
            public void onClick(View v) {
                //onClickLeft();
                Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_SHORT).show();
            }
        });


        // Recognizer initialization is a time-consuming and it involves IO,
        // so we execute it in async task
        //if(!tts.isSpeaking()) {
        new AsyncTask<Void, Void, Exception>() {
            @Override
            protected Exception doInBackground(Void... params) {
                try {
                    Assets assets = new Assets(Sam.this);
                    File assetDir = assets.syncAssets();
                    Log.v("AsyncTask", "AsyncTask");
                    setupRecognizer(assetDir);

                } catch (IOException e) {
                    return e;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Exception result) {
                Log.v("onPostExecute", "onPostExecute");
                try{
                    if (result != null) {
                        //caption_text.setText("Failed to init recognizer " + result);
                        Toast.makeText(getApplicationContext(), "Failed to init recognizer ", Toast.LENGTH_SHORT).show();
                    } else {
                        FireRecognition();
                        //switchSearch(DIGITS_SEARCH);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.execute();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("onDestroy", "onDestroy");
        recognizer.cancel();
        recognizer.shutdown();

        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
    }

    public void FireRecognition(){
        Log.d("Recognition","Recognition Started");
        //caption_text.setText("Recognition Started!");
        //Toast.makeText(getApplicationContext(), "Recognition Started!", Toast.LENGTH_SHORT).show();
        recognizer.stop();
        //recognizer.startListening("digits");

    }

    /**
     * In partial result we get quick updates about current hypothesis. In
     * keyword spotting mode we can react here, in other modes we need to wait
     * for final result in onResult.
     */
    @Override
    public void onPartialResult(Hypothesis hypothesis) {
        try {
            //Log.v("onPartialResult", "onPartialResult");
            if (hypothesis == null)
                return;
            Log.v("onPartialResult", hypothesis.getHypstr().toString());

            String text = hypothesis.getHypstr();
            if(recognizer !=null)
                recognizer.stop();

            caption_text.setText("Partial result -->: " + text);

            Log.v("onPartialResult-->", text);

            //   Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This callback is called when we stop the recognizer.
     */
    @Override
    public void onResult(Hypothesis hypothesis) {
        try{
            Log.v("onResult", "onResult");
            //  result_text.setText("");
            if (hypothesis != null) {
                String text = hypothesis.getHypstr();
                //Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                //  ((TextView) findViewById(R.id.result_text)).setText(text);

                if(text.toLowerCase().equals("next")) {
                    result_text.setText("Result --->: " + text);
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                } else if(text.toLowerCase().equals("previous")) {
                    result_text.setText("Result --->: " + text);
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

                } else if(text.toLowerCase().trim().equals("option one".toLowerCase().trim())) {
                    result_text.setText("Result --->: " + text);


                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                    result_text.setText("Result --->: " + text);
                } else if(text.toLowerCase().trim().equals("option two".toLowerCase().toString())) {

                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                } else if(text.toLowerCase().trim().equals("option three".toLowerCase().toString())) {
                    result_text.setText("Result --->: " + text);
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                } else if(text.toLowerCase().trim().equals("option four".toLowerCase().toString())) {
                    result_text.setText("Result --->: " + text);
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), " No Access:--" + text, Toast.LENGTH_SHORT).show();
                }




                Log.v("onResult-->", text);
                if(recognizer != null)              
                    recognizer.startListening("digits");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBeginningOfSpeech() {
        Log.v("onBeginningOfSpeech", "onBeginningOfSpeech");

    }

    /**
     * We stop recognizer here to get a final result
     */
    @Override
    public void onEndOfSpeech() {
        Log.v("onEndOfSpeech", "onEndOfSpeech");

        if (!recognizer.getSearchName().equals(DIGITS_SEARCH))
            switchSearch(DIGITS_SEARCH);
    }


    private void switchSearch(String searchName) {
        Log.v("switchSearch", "switchSearch--->" + searchName);
        recognizer.stop();

        // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
        if (searchName.equals(DIGITS_SEARCH))
            recognizer.startListening(searchName, 10000);
        /* else
            recognizer.startListening(searchName, 10000);*/

        /* String caption = getResources().getString(captions.get(searchName));
        caption_text.setText(caption);*/
    }

    private void setupRecognizer(File assetsDir) throws IOException {

        // The recognizer can be configured to perform multiple searches
        // of different kind and switch between them
        Log.v("setupRecognizer", "setupRecognizer");
        recognizer = defaultSetup()
                .setAcousticModel(new File(assetsDir, "en-us-ptm"))
                .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))

                // To disable logging of raw audio comment out this call (takes a lot of space on the device)
                .setRawLogDir(assetsDir)

                // Threshold to tune for keyphrase to balance between false alarms and misses
                .setKeywordThreshold(1e-20f) //1e-20f 1e-45f

                // Use context-independent phonetic search, context-dependent is too slow for mobile
                // .setBoolean("-allphone_ci", true)

                .getRecognizer();
        recognizer.addListener(this);

        /** In your application you might not need to add all those searches.
         * They are added here for demonstration. You can leave just one.
         */

        // Create keyword-activation search.
        // recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);



        // Create grammar-based search for digit recognition
        File digitsGrammar = new File(assetsDir, "digits.gram");
        recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);

    }



    @Override
    public void onError(Exception error) {
        Log.v("onError", "onError");
        //caption_text.setText(error.getMessage());
        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTimeout() {
        Log.v("onTimeout", "onTimeout");
        switchSearch(DIGITS_SEARCH);
    }


    @SuppressWarnings("deprecation")
    @Override
    public void onInit(int status) {

        tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

            @Override
            public void onUtteranceCompleted(String utteranceId) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(recognizer != null)
                            recognizer.startListening("digits");
                        //Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });

        if (status == TextToSpeech.SUCCESS) {  

            int result = tts.setLanguage(Locale.US);  


            Log.i("Success", "Completed");

            if (result == TextToSpeech.LANG_MISSING_DATA  || result == TextToSpeech.LANG_NOT_SUPPORTED) {  
                Log.e("TTS", "This Language is not supported");  
            } else {  
                //buttonSpeak.setEnabled(true);  
                //  speakOut();  
                String text = " No Voice Found".toString();
                Log.i("else", "else");
                // speakOut(text);  
            }  

        } else {  
            Log.e("TTS", "Initilization Failed!");  
        }  

    }


    @SuppressWarnings("deprecation")
    private void speakOut(String text) {
        if(tts.isSpeaking()) {
            //recognizer.stop();
        }
        //  String text =  ((TextView) findViewById(R.id.caption_text)).getText().toString();
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, params);

        Log.i("Speaking-->", "****" + tts.isSpeaking());

    } 



}

And in digit.gram

#JSGF V1.0;

grammar digits;

<digit> = option one |
          option two |
          option three |
          option four |
          back |
          previous |
          next;

public <digits> = <digit>+;

Above is my code if any one worked on it please let me know the solution Here is my xml quiz.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/linearLayout1"
        android:orientation="vertical" >

        <ExpandableListView
            android:id="@+id/listViewAnswer"
            android:layout_width="match_parent"
            android:layout_height="301dp"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:childDivider="#334455" >
        </ExpandableListView>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="10dip"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/buttonRight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dip"
            android:text="Next" />

        <Button
            android:id="@+id/buttonLeft"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text="Previous" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout1" >

        <TextView
            android:id="@+id/result_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#556677" />

        <TextView
            android:id="@+id/caption_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/result_text"
            android:layout_alignParentLeft="true"
            android:textColor="#443399" />
    </RelativeLayout>

</RelativeLayout>

Update:

if u are using addKeywordSearch

File digitsGrammar = new File(context.getFilesDir(), "digits.gram");
recognizer.addKeywordSearch(DIGITS_SEARCH, digitsGrammar);

then in digit.gram write only

 option one /1e-1/
 option two /1e-1/
 option three /1e-1/
 option four /1e-1/
 back /1e-1/
 previous /1e-1/
 next /1e-1/

or

if you are using addGrammarSearch

 File digitsGrammar = new File(context.getFilesDir(), "digits.gram");
 recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);

then in digit.gram

#JSGF V1.0;

grammar digits;

<digit> = option one |
      option two |
      option three  |
      option four |
      back  |
      previous |
      next;

     public <digits> = <digit>+;

解决方案

You need to use keyword spotting mode instead of grammar mode for continuous listening

You can find example here:

Recognizing multiple keywords using PocketSphinx

阅读全文

相关推荐

最新文章