android pocketsphinx不发送结果或部分结果

时间:2017-01-25 04:00:57

标签: android speech-recognition cmusphinx

见下面的代码。 Pocketsphinx配置了一个关键短语搜索来触发单词"记录"。然后开始搜索,并且调用会导致调用onBeginningOfSpeechonEndOfSpeech,但不管我说什么,都不会调用其他侦听器方法。

public class MainActivity extends AppCompatActivity implements RecognitionListener {
    private final Handler handler = new Handler ();
    private SpeechRecognizer recognizer;
    private final static String KEYWORD = "record";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        makeButtonStartButton ();

        ensureRecordAudioPermission ();
        startKeywordListener ();
    }

    private void startKeywordListener() {
        // Recognizer initialization is a time-consuming and it involves IO,
        // so we execute it in async task
        new AsyncTask<Void, Void, Exception>() {
            @Override
            protected Exception doInBackground(Void... params) {
                try {
                    Assets assets = new Assets(MainActivity.this);
                    File assetDir = assets.syncAssets();
                    setupRecognizer(assetDir);
                } catch (IOException e) {
                    return e;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Exception result) {
                if (result != null) {
                    Log.e("MainActivity", "Failed to init recognizer " + result);
                } else {
                    startKeywordSearch ();
                }
            }
        }.execute();

    }

    private void startKeywordSearch() {
        Log.i("MainActivity", "Starting keyword search: " + KEYWORD);
        recognizer.stop();
        recognizer.startListening(KEYWORD);
    }

    private void setupRecognizer(File assetsDir) throws IOException {
        // The recognizer can be configured to perform multiple searches
        // of different kind and switch between them

        recognizer = SpeechRecognizerSetup.defaultSetup()
                .setAcousticModel(new File(assetsDir, "en-us-ptm"))
                .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))

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

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

        // Create keyword-activation search.
        recognizer.addKeyphraseSearch(KEYWORD, KEYWORD);
    }

    private void ensureRecordAudioPermission() {
        // Check if user has given permission to record audio
        int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
        if (permissionCheck == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            return;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startKeywordListener();
            } else {
                finish();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (recognizer != null) {
            recognizer.cancel();
            recognizer.shutdown();
        }
    }
    private void makeButtonStartButton() {
        findViewById(R.id.startButton).setOnClickListener(startRecording);
    }
    private final View.OnClickListener startRecording = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, RecordingActivity.class));
        }
    };

    @Override
    public void onBeginningOfSpeech() {
        Log.i ("MainActivity", "Beginning of speech detected");
    }

    @Override
    public void onEndOfSpeech() {
        Log.i ("MainActivity", "End of speech detected");
    }

    @Override
    public void onPartialResult(Hypothesis hypothesis) {
        if (hypothesis == null) return; // reject the null hypothesis (!)
        Log.i ("MainActivity", "Partial result: " + hypothesis.getHypstr() + " (" + hypothesis.getProb() + ")");
        if (hypothesis.getHypstr().equals(KEYWORD))
            startRecording.onClick(null);
    }

    @Override
    public void onResult(Hypothesis hypothesis) {
        if (hypothesis == null) return; // reject the null hypothesis (!)
        Log.i ("MainActivity", "Complete result: " + hypothesis.getHypstr() + " (" + hypothesis.getProb() + ")");
        if (hypothesis.getHypstr().equals(KEYWORD))
            startRecording.onClick(null);

    }

    @Override
    public void onError(Exception e) {
        Log.i ("MainActivity", "Error detected", e);
    }

    @Override
    public void onTimeout() {
        Log.i ("MainActivity", "Timeout occurred");
    }
}

0 个答案:

没有答案