【问题标题】:using voice command in android how to navigate pages在android中使用语音命令如何导航页面
【发布时间】:2012-06-13 06:43:29
【问题描述】:

我想开发一个应用程序来使用语音命令将一个页面导航到另一个页面

这是我的代码

 public class mainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */

 ArrayList<String> StoredCommand = new ArrayList<String>();

private static final String TAG = "VoiceRecognition";

private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

private static final Context View = null;

private ListView mList;

private Handler mHandler;

private Spinner mSupportedLanguageView;

/**
 * Called with the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHandler = new Handler();

    StoredCommand.add("Path Recoder");
    StoredCommand.add("Path Selector");
    StoredCommand.add("Stop");
    StoredCommand.add("Pause");


    // Inflate our UI from its XML layout description.
    setContentView(R.layout.main);

    // Get display items for later interaction
    Button speakButton = (Button) findViewById(R.id.btn_speak);

    mList = (ListView) findViewById(R.id.list);

    mSupportedLanguageView = (Spinner) findViewById(R.id.supported_languages);

    // Check to see if a recognition activity is present
    PackageManager pm = getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (activities.size() != 0) {
        speakButton.setOnClickListener(this);
    } else {
        speakButton.setEnabled(false);
        speakButton.setText("Recognizer not present");
    }

    // Most of the applications do not have to handle the voice settings. If the application
    // does not require a recognition in a specific language (i.e., different from the system
    // locale), the application does not need to read the voice settings.
    refreshVoiceSettings();
}

/**
 * Handle the click on the start recognition button.
 */
public void onClick(View v) {
    if (v.getId() == R.id.btn_speak) {
        startVoiceRecognitionActivity();
    }
}

/**
 * Fire an intent to start the speech recognition activity.
 */
private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

    // Specify the calling package to identify your application
    intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());

    // Display an hint to the user about what he should say.
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");

    // Given an hint to the recognizer about what the user is going to say
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

    // Specify how many results you want to receive. The results will be sorted
    // where the first result is the one with higher confidence.
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);

    // Specify the recognition language. This parameter has to be specified only if the
    // recognition has to be done in a specific language and not the default one (i.e., the
    // system locale). Most of the applications do not have to set this parameter.
    if (!mSupportedLanguageView.getSelectedItem().toString().equals("Default")) {
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                mSupportedLanguageView.getSelectedItem().toString());
    }

    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

/**
 * Handle the results from the recognition activity.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {

        // Fill the list view with the strings the recognizer thought it could have heard
        ArrayList<String> matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);
        mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
               matches));

        StringBuilder sb=new StringBuilder()  ;
        for (String match:matches){


        switch(resultCode) {
        case RESULT_OK:
            Log.i(TAG, "RESULT_OK");

            if(StoredCommand==matches)
            {
                //Button next=(Button)findViewById(R.id.btn_speak);
                 if (matches.contains("Path Recoder"))
                {

                 Intent myIntent = new Intent(View, PahtRecoder.class);
                 startActivityForResult(myIntent, 0);
                }

                 else if(matches.contains("path selector"))
                 {
                     Intent myIntent = new Intent(View, Pahtselector.class);
                     startActivityForResult(myIntent, 0);

                 }
                 else if(matches.contains("stop"))
                 {
                     Intent myIntent = new Intent(View, Pahtselector.class);
                     startActivityForResult(myIntent, 0);

                 }
                 else if(matches.contains("start"))

                 {

                     Intent myIntent = new Intent(View, Pahtselector.class);
                     startActivityForResult(myIntent, 0);
                 }
                 }



            else
            {
                Log.i(TAG, "COMMAND_NOT_MATCHING");
            }


            break;
        case RESULT_CANCELED:
            Log.i(TAG, "RESULT_CANCELED");
            break;
        case RecognizerIntent.RESULT_AUDIO_ERROR:
            Log.i(TAG, "RESULT_AUDIO_ERROR");
            break;
        case RecognizerIntent.RESULT_CLIENT_ERROR:
            Log.i(TAG, "RESULT_CLIENT_ERROR");
            break;
        case RecognizerIntent.RESULT_NETWORK_ERROR:
            Log.i(TAG, "RESULT_NETWORK_ERROR");
            break;
        case RecognizerIntent.RESULT_NO_MATCH:
            Log.i(TAG, "RESULT_NO_MATCH");
            break;
        case RecognizerIntent.RESULT_SERVER_ERROR:
            Log.i(TAG, "RESULT_SERVER_ERROR");
            break;
        default:
            Log.i(TAG, "RESULT_UNKNOWN");
            break;
        }




        }

    }





    else{
        Log.e("TAG", "Recognition is Failed");
    }

    super.onActivityResult(requestCode, resultCode, data);
}

private void refreshVoiceSettings() {
    Log.i(TAG, "Sending broadcast");
    sendOrderedBroadcast(RecognizerIntent.getVoiceDetailsIntent(this), null,
            new SupportedLanguageBroadcastReceiver(), null, Activity.RESULT_OK, null, null);
}

private void updateSupportedLanguages(List<String> languages) {
    // We add "Default" at the beginning of the list to simulate default language.
    languages.add(0, "Default");

    SpinnerAdapter adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, languages.toArray(
                    new String[languages.size()]));
    mSupportedLanguageView.setAdapter(adapter);
}

private void updateLanguagePreference(String language) {
    TextView textView = (TextView) findViewById(R.id.language_preference);
    textView.setText(language);
}

/**
 * Handles the response of the broadcast request about the recognizer supported languages.
 *
 * The receiver is required only if the application wants to do recognition in a specific
 * language.
 */
private class SupportedLanguageBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, final Intent intent) {
        Log.i(TAG, "Receiving broadcast " + intent);

        final Bundle extra = getResultExtras(false);

        if (getResultCode() != Activity.RESULT_OK) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    showToast("Error code:" + getResultCode());
                }
            });
        }

        if (extra == null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    showToast("No extra");
                }
            });
        }

        if (extra.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    updateSupportedLanguages(extra.getStringArrayList(
                            RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES));
                }
            });
        }

        if (extra.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    updateLanguagePreference(
                            extra.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
                }
            });
        }
    }

    private void showToast(String text) {

        Toast.makeText(mainActivity.this, text, 1000).show();
    }
}

根据存储的命令,我需要导航这些页面。但结果是谷歌语音选项工作但命令不起作用。我的模式匹配有什么问题......请给我解决方案。 谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    试试这个作为onActivityResult()的最小实现:

    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK)
    {
        ArrayList<String> matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);
        mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                   matches));
        for (String bestMatch:matches)
        {
            if (bestMatch.equalsIgnoreCase("Path Recoder"))
            {
                Intent myIntent = new Intent(View, PahtRecoder.class);
                startActivityForResult(myIntent, 0);
            }
            else if(bestMatch.equalsIgnoreCase("Path Selector"))
            {
                Intent myIntent = new Intent(View, Pahtselector.class);
                startActivityForResult(myIntent, 0);
            }
            else if(bestMatch.equalsIgnoreCase("Stop"))
            {
                Intent myIntent = new Intent(View, Pahtselector.class);
                startActivityForResult(myIntent, 0);
            }
            else if(bestMatch.equalsIgnoreCase("Pause"))
            {
                Intent myIntent = new Intent(View, Pahtselector.class);
                startActivityForResult(myIntent, 0);
            }
            else
            {
                Log.i(TAG, "COMMAND_NOT_MATCHING");
            }
        }
    }
    

    进一步更新:我最初的帖子是错误的-不应使用StoredCommand;在较旧的语音识别平台上,他们将获得一份可能的话语列表,并且引擎会尝试将您所说的内容与可能性相匹配。但是,Android 上的默认引擎不需要这个。顺便问一下,你的mList 显示什么?

    另外请注意,我还没有测试过上面的任何代码...

    【讨论】:

    • 当用户说“路径重新编码器”时,它应该导航到路径重新编码器页面。这就是我想要的。我在名为 StoredCommand 的数组列表中存储了命令。如果你这么说,那么告诉我应该做什么我愿意。你能编辑这个或给我解决方案吗。谢谢
    • 我已经更新了我的答案,所以请注意StoredCommand 从未被引擎使用过;默认的 Google Voice 不使用输入提示。
    • 但使用谷歌语音很难识别我们所说的内容。如果我们说“停止”,它不会在列表视图中生成停用词。所以无法导航到页面。所以我如何得到正确的词列表视图。
    • @KavindiWicramasingha 这是一个非常好的问题!如果有更受限制的模式可用,那就太好了。 Pocket Sphinx 似乎是一种选择 - 这里是 similar question from two years ago,所以您也许可以再次询问,看看最先进的技术是否有所改进 - this non-answer 是您所追求的,我想?
    • 对不起,另一个评论 - 这里是a promising question and answer from this April
    【解决方案2】:

    大家好,这是使用语音命令从一个页面导航到另一个页面的代码。它对任何人都有用

    公共类 mainActivity 扩展 Activity 实现 OnClickListener { /** 在第一次创建活动时调用。 */

    private static final String TAG = "VoiceRecognition";
    
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    
    private static final Context View = null;
    
    private ListView mList;
    
    private Handler mHandler;
    
    private Spinner mSupportedLanguageView;
    
    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    
    
    
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.main);
    
        // Get display items for later interaction
        Button speakButton = (Button) findViewById(R.id.btn_speak);
    
        mList = (ListView) findViewById(R.id.list);
    
        mSupportedLanguageView = (Spinner) findViewById(R.id.supported_languages);
    
        // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() != 0) {
            speakButton.setOnClickListener(this);
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }
    
        // Most of the applications do not have to handle the voice settings. If the application
        // does not require a recognition in a specific language (i.e., different from the system
        // locale), the application does not need to read the voice settings.
        refreshVoiceSettings();
    }
    
    /**
     * Handle the click on the start recognition button.
     */
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            startVoiceRecognitionActivity();
        }
    }
    
    /**
     * Fire an intent to start the speech recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    
        // Specify the calling package to identify your application
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
    
        // Display an hint to the user about what he should say.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
    
        // Given an hint to the recognizer about what the user is going to say
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    
        // Specify how many results you want to receive. The results will be sorted
        // where the first result is the one with higher confidence.
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
    
        // Specify the recognition language. This parameter has to be specified only if the
        // recognition has to be done in a specific language and not the default one (i.e., the
        // system locale). Most of the applications do not have to set this parameter.
        if (!mSupportedLanguageView.getSelectedItem().toString().equals("Default")) {
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                    mSupportedLanguageView.getSelectedItem().toString());
        }
    
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }
    
    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
    
            // Fill the list view with the strings the recognizer thought it could have heard
             ArrayList<String> matches = data.getStringArrayListExtra(
                        RecognizerIntent.EXTRA_RESULTS);
                mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                           matches));
               for (String bestMatch : matches) {
                    if (bestMatch.contains("record") || bestMatch.contains("cod") || bestMatch.contains("ed")) {
                        // Intent myIntent = new Intent(View, PahtRecoder.class);
                        // startActivityForResult(myIntent, 0);
                        Intent my = new Intent(getApplicationContext(),
                                PathRecorderStart.class);
                        startActivityForResult(my, 0);
                    }
    
                    else if (bestMatch.contains("select") || bestMatch.contains("elect") || bestMatch.contains("ct")) {
                        // Intent myIntent = new Intent(View, PahtRecoder.class);
                        // startActivityForResult(myIntent, 0);
                        Intent my = new Intent(getApplicationContext(),
                                PathSelectorOptions.class);
                        startActivityForResult(my, 0);
                    }
    
                    else {
                        Log.i(TAG, "COMMAND_NOT_MATCHING");
                    }
    
                }
        }
    
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    private void refreshVoiceSettings() {
        Log.i(TAG, "Sending broadcast");
        sendOrderedBroadcast(RecognizerIntent.getVoiceDetailsIntent(this), null,
                new SupportedLanguageBroadcastReceiver(), null, Activity.RESULT_OK, null, null);
    }
    
    private void updateSupportedLanguages(List<String> languages) {
        // We add "Default" at the beginning of the list to simulate default language.
        languages.add(0, "Default");
    
        SpinnerAdapter adapter = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_item, languages.toArray(
                        new String[languages.size()]));
        mSupportedLanguageView.setAdapter(adapter);
    }
    
    private void updateLanguagePreference(String language) {
        TextView textView = (TextView) findViewById(R.id.language_preference);
        textView.setText(language);
    }
    
    /**
     * Handles the response of the broadcast request about the recognizer supported languages.
     *
     * The receiver is required only if the application wants to do recognition in a specific
     * language.
     */
    private class SupportedLanguageBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, final Intent intent) {
            Log.i(TAG, "Receiving broadcast " + intent);
    
            final Bundle extra = getResultExtras(false);
    
            if (getResultCode() != Activity.RESULT_OK) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        showToast("Error code:" + getResultCode());
                    }
                });
            }
    
            if (extra == null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        showToast("No extra");
                    }
                });
            }
    
            if (extra.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) {
                mHandler.post(new Runnable() {
    
                    @Override
                    public void run() {
                        updateSupportedLanguages(extra.getStringArrayList(
                                RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES));
                    }
                });
            }
    
            if (extra.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) {
                mHandler.post(new Runnable() {
    
                    @Override
                    public void run() {
                        updateLanguagePreference(
                                extra.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
                    }
                });
            }
        }
    
        private void showToast(String text) {
    
            Toast.makeText(mainActivity.this, text, 1000).show();
        }
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2014-03-06
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多