在后台安装Android语音识别并转换为文本

时间:2017-07-29 08:46:57

标签: android background voice-recognition

我有一个应用程序的想法,可识别来自Android操作系统的人声并将语音转换为文本。我已经在前台完成了这个过程。但我需要在背景中实现。

为此,我认为这个方法。我的方法是获取活动背景状态,然后从那里调用服务。之后每当应用程序将在每次调用服务时都在后台。 我不知道如何实现这一点。

我的前景源代码

private void promptSpeechInput(){
                //----takes user input----//
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                //----which language users will speak
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                //-----
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                        getString(R.string.speech_prompt));
                try {
                    startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
                } catch (ActivityNotFoundException a) {
                    Toast.makeText(getApplicationContext(),
                            getString(R.string.speech_not_supported),
                            Toast.LENGTH_SHORT).show();
                }
            }
   /**
     * Receiving speech input
     * */


  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case REQ_CODE_SPEECH_INPUT: {
            if (resultCode == RESULT_OK && null != data) {
           ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                  txtSpeechInput.setText(result.get(0));
            }
            break;
        }

    }
}

service

致电activity
 @Override
        protected void onPause(){
            super.onPause();
            Log.e("Application background", "Background");
            //-----Create Service From here and identify the state of background
           Intent serviceIntent = new Intent(this,BackgroundService.class);
           startService(serviceIntent);
    }

BackgroundService.java

public class BackgroundService extends Service {
    private SpeechRecognizer speech;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Log.e("servicecreate", "service");
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        Log.e("servicedestroy", "service");
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("servicecstart", "service");
    }
}

0 个答案:

没有答案