Приложение TextToSpeech. Вызов без интерфейса - PullRequest
2 голосов
/ 12 марта 2012

Как вызвать класс TextToSpeech из другого класса, когда класс TextToSpeech не имеет пользовательского интерфейса. В приложении есть только один макет, который использует основной класс. Теперь моя задача - заставить приложение говорить и взаимодействовать с пользователем в соответствии с ситуацией ..

Ответы [ 2 ]

0 голосов
/ 13 марта 2012

Для использования TextToSpeech вам не требуется пользовательский интерфейс или действие.

0 голосов
/ 12 марта 2012
      //decleration
  TextToSpeech talker;
Button speakButton;

//onCreate
talker = new TextToSpeech(this, this);
    speakButton=new Button(this);

 // 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(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                startVoiceRecognitionActivity();
            }
        });
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }


/**
     * Fire an intent to start the speech 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, "Speech recognition demo");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);


    }

/**
     * Handle the results from the recognition activity.
     */

    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);

          //  Toast.makeText(VoiceRecognition.this, matches.get(0), 5000).show();
        String device = "Bedroom";
          /*  mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
         matches));     
            */
            txt.setText(""+matches.get(0));
            String host = "http://web2.anzleads.com/Android/nimboPani/web-service.php?tmote=";
            String userCommand = URLEncoder.encode(matches.get(0));
            String deviceSelected = "&org=" + device;
           res =  getServerResponse(host + userCommand + deviceSelected);
           say(""+ res);
            Toast.makeText(VoiceRecognition.this,res ,5000).show();


        }

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


    public void say(String text2say){
                  talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
                }


    public void onInit(int status) {
        // TODO Auto-generated method stub
    //  say("Hello World");
    }


           public void onDestroy() {
          if (talker != null) {
                 talker.stop();
                 talker.shutdown();
              }

              super.onDestroy();
           }
 public String getServerResponse(String url)
    {
        String result = "";
        HttpClient hc = new DefaultHttpClient();
        HttpResponse hr ;
        HttpGet hg = new HttpGet(url);
        try
        {
            hr = hc.execute(hg);
            if(hr.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity he = hr.getEntity();
                if (he != null)
                {
                    InputStream is = he.getContent();
                      result = convertStreamToString(is);
                      is.close();

                }
            }
        }



        catch (Exception e) {
            // TODO: handle exception
        }

         return result;

    }


    private String convertStreamToString(InputStream instream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
        StringBuilder sb = new StringBuilder();


        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();

    }
...