2014-11-06 2 views
0

Я совершенно не знаком с Android, и я решил создать приложение для поиска Siri, которое отлично работает, я искал, прежде чем спрашивать, но я не могу заставить его работать: Android speech Recognition App Without Pop UpИзменение распознавания речи без всплывающего окна

Так что я хочу скрыть всплывающее окно в своем приложении для Android, но я действительно не понимаю, как это сделать должным образом. Я буду очень рад, если кто-то поможет мне в этом. Я уже добавил необходимые разрешения в Android Manifest ...

Вот мой полный источник:

/** 
* Giovanni Terlingen 
* PWS Project 
* 3 november 2014 
* Original file from http://github.com/gi097/PWS 
*/ 
package nl.giovanniterlingen.pws; 

import java.util.ArrayList; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.speech.RecognizerIntent; 
import android.speech.tts.TextToSpeech; 
import android.speech.tts.TextToSpeech.OnInitListener; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class Main extends Activity implements OnInitListener { 
    private static final String TAG = "PWS"; 

    private TextView result; 

    private TextToSpeech tts; 

    private Button speak; 

    private int SPEECH_REQUEST_CODE = 1234; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     speak = (Button) findViewById(R.id.bt_speak); 
     speak.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       sendRecognizeIntent(); 
      } 
     }); 

     speak.setEnabled(false); 
     result = (TextView) findViewById(R.id.tv_result); 

     tts = new TextToSpeech(this, this); 
    } 

    @Override 
    public void onInit(int status) { 
     if (status == TextToSpeech.SUCCESS) { 
      speak.setEnabled(true); 
     } else { 
      // failed to init 
      finish(); 
     } 

    } 

    private void sendRecognizeIntent() { 
     Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
     intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
       RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
     intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren..."); 
     intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100); 
     startActivityForResult(intent, SPEECH_REQUEST_CODE); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == SPEECH_REQUEST_CODE) { 
      if (resultCode == RESULT_OK) { 
       ArrayList<String> matches = data 
         .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); 

       if (matches.size() == 0) { 
        tts.speak("Ik heb niks gehoord, probeer het nog eens", 
          TextToSpeech.QUEUE_FLUSH, null); 
       } else { 
        String mostLikelyThingHeard = matches.get(0); 
        result.setText("Dit heeft u gezegd: " 
          + mostLikelyThingHeard + "."); 
        mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase(); 
        boolean found = false; 

        String[] groeten = { "hallo", "heey", "hoi", "hey", "he", 
          "hee", "hay" }; 
        for (String strings : groeten) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Hey leuk dat je er bent!", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        String[] okay = { "oké, oke, ok, okay, okee" }; 
        for (String strings : okay) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Okiedokie!", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        String[] vragen = { "hoe gaat het", "hoe gaat het met je", "hoe gaat het met jou", "hoe gaat het met u", "hoe is het"}; 
        for (String strings : vragen) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Met mij gaat het altijd goed, met jou?", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        String[] wie = { "wie ben", "hoe heet je", "hoe heet jij", "wat is je naam", "wat is uw naam"}; 
        for (String strings : wie) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Ik ben PWS, ik ben gemaakt als profielwerkstuk door Giovanni Terlingen.", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        String[] leeftijd = { "hoe oud ben" }; 
        for (String strings : leeftijd) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Ik ben op 3 november 2014 van start gegaan dus dat mag je zelf uitrekenen", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        String[] lachen = { "haha", "hah", "ha" }; 
        for (String strings : okay) { 
         if (mostLikelyThingHeard.contains(strings)) { 
          tts.speak("Haha leuk grapje", 
            TextToSpeech.QUEUE_FLUSH, null); 
          found = true; 
          break; 
         } 
        } 
        if (!found) { 
         String doei = "doei"; 
         if (mostLikelyThingHeard.equals(doei)) { 
          tts.speak("Okay tot de volgende keer!", 
            TextToSpeech.QUEUE_FLUSH, null); 
         } else { 
          tts.speak("Ik begrijp niet wat je bedoeld met " 
            + mostLikelyThingHeard 
            + " probeer het anders te verwoorden.", 
            TextToSpeech.QUEUE_FLUSH, null); 
         } 
        } 

       } 
      } 
     } else { 
      Log.d(TAG, "result NOT ok"); 
     } 

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

    @Override 
    protected void onDestroy() { 
     if (tts != null) { 
      tts.shutdown(); 
     } 
     super.onDestroy(); 
    } 
} 

ответ

0

Шаг 1

В Android Manifest.xml, добавить разрешение.

<uses-permission android:name="android.permission.RECORD_AUDIO" /> 

Шаг 2 На экране Макет я с помощью кнопки переключения для запуска/остановки голосового прослушивания.

<?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" > 

    ....... 

    <ToggleButton 
     android:id="@+id/toggleButton1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="26dp" 
     android:text="ToggleButton" /> 

...... 

</RelativeLayout> 

Шаг 3 - Класс активности

пакет com.example.voice;

import java.util.ArrayList; 

import android.speech.RecognitionListener; 
import android.speech.RecognizerIntent; 
import android.speech.SpeechRecognizer; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.CompoundButton; 
import android.widget.CompoundButton.OnCheckedChangeListener; 
import android.widget.ProgressBar; 
import android.widget.TextView; 
import android.widget.ToggleButton; 

public class VoiceRecognitionActivity extends Activity implements 
     RecognitionListener { 

    private TextView returnedText; 
    private ToggleButton toggleButton; 

    private SpeechRecognizer speech = null; 
    private Intent recognizerIntent; 
    private String LOG_TAG = "VoiceRecognitionActivity"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     returnedText = (TextView) findViewById(R.id.textView1); 
     toggleButton = (ToggleButton) findViewById(R.id.toggleButton1); 

     speech = SpeechRecognizer.createSpeechRecognizer(this); 
     speech.setRecognitionListener(this); 
     recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
     recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, 
       "en"); 
     recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, 
       this.getPackageName()); 
     recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
       RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); 
     recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); 

     toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

      @Override 
      public void onCheckedChanged(CompoundButton buttonView, 
        boolean isChecked) { 
       if (isChecked) { 

        speech.startListening(recognizerIntent); 
       } else { 
                        speech.stopListening(); 
       } 
      } 
     }); 

    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     if (speech != null) { 
      speech.destroy(); 
      Log.i(LOG_TAG, "destroy"); 
     } 

    } 

    @Override 
    public void onBeginningOfSpeech() { 
     Log.i(LOG_TAG, "onBeginningOfSpeech"); 
       } 

    @Override 
    public void onBufferReceived(byte[] buffer) { 
     Log.i(LOG_TAG, "onBufferReceived: " + buffer); 
    } 

    @Override 
    public void onEndOfSpeech() { 
     Log.i(LOG_TAG, "onEndOfSpeech"); 
     toggleButton.setChecked(false); 
    } 

    @Override 
    public void onError(int errorCode) { 
     String errorMessage = getErrorText(errorCode); 
     Log.d(LOG_TAG, "FAILED " + errorMessage); 
     returnedText.setText(errorMessage); 
     toggleButton.setChecked(false); 
    } 

    @Override 
    public void onEvent(int arg0, Bundle arg1) { 
     Log.i(LOG_TAG, "onEvent"); 
    } 

    @Override 
    public void onPartialResults(Bundle arg0) { 
     Log.i(LOG_TAG, "onPartialResults"); 
    } 

    @Override 
    public void onReadyForSpeech(Bundle arg0) { 
     Log.i(LOG_TAG, "onReadyForSpeech"); 
    } 

    @Override 
    public void onResults(Bundle results) { 
     Log.i(LOG_TAG, "onResults"); 
     ArrayList<String> matches = results 
       .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); 
     String text = ""; 
     for (String result : matches) 
      text += result + "\n"; 

     returnedText.setText(text); 
    } 

    @Override 
    public void onRmsChanged(float rmsdB) { 
     Log.i(LOG_TAG, "onRmsChanged: " + rmsdB); 
    } 

    public static String getErrorText(int errorCode) { 
     String message; 
     switch (errorCode) { 
     case SpeechRecognizer.ERROR_AUDIO: 
      message = "Audio recording error"; 
      break; 
     case SpeechRecognizer.ERROR_CLIENT: 
      message = "Client side error"; 
      break; 
     case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: 
      message = "Insufficient permissions"; 
      break; 
     case SpeechRecognizer.ERROR_NETWORK: 
      message = "Network error"; 
      break; 
     case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: 
      message = "Network timeout"; 
      break; 
     case SpeechRecognizer.ERROR_NO_MATCH: 
      message = "No match"; 
      break; 
     case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: 
      message = "RecognitionService busy"; 
      break; 
     case SpeechRecognizer.ERROR_SERVER: 
      message = "error from server"; 
      break; 
     case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: 
      message = "No speech input"; 
      break; 
     default: 
      message = "Didn't understand, please try again."; 
      break; 
     } 
     return message; 
    } 

} 
+0

Хорошо, я уже пробовал, но мне нужно слить его в исходный код правильно: p –

Смежные вопросы