/** * Loads a compiled grammar from a file. * * @param grammar A file representing the compiled G2G-formatted grammar. * @return <code>true</code> on success */ public boolean loadGrammar(File grammar) { boolean successful = false; // Check directory contents... String[] contents = grammar.getParentFile().list(); for (String content : contents) { Log.e(TAG, content); } mGrammar = grammar; String path = mGrammar.getPath(); try { mSrec = new Recognizer(SREC_DIR + "/baseline11k.par"); mSrecGrammar = mSrec.new Grammar(path); mSrecGrammar.setupRecognizer(); mSrecGrammar.resetAllSlots(); successful = true; } catch (IllegalStateException e) { Log.e(TAG, e.toString()); String[] contents2 = grammar.getParentFile().list(); for (String content : contents2) { Log.e(TAG, "+" + content); } e.printStackTrace(); } catch (IOException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } if (!successful) { if (mSrecGrammar != null) { mSrecGrammar.destroy(); } if (mSrec != null) { mSrec.destroy(); } mSrecGrammar = null; mGrammar = null; mSrec = null; } return successful; }
/** * Loads the available slots in a grammar using the entries in the supplied GrammarMap. You must * load a grammar before calling this method. * * @param map A populated GrammarMap object. * @return <code>true</code> on success */ public boolean loadSlots(GrammarMap map) { Context context = mContext.get(); Resources res = context.getResources(); File cached = context.getFileStreamPath("compiled." + EXTENSION_G2G); cached.deleteOnExit(); for (Entry<String, List<GrammarEntry>> pair : map.getEntries()) { String slot = pair.getKey(); List<GrammarEntry> entries = pair.getValue(); for (GrammarEntry entry : entries) { mSrecGrammar.addWordToSlot(slot, entry.word, entry.pron, entry.weight, entry.tag); } } // Attempt to compile and save grammar to cache try { mSrecGrammar.compile(); cached.getParentFile().mkdirs(); mSrecGrammar.save(cached.getPath()); Log.i(TAG, "Compiled grammar to " + cached.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); return false; } // Destroy the old grammar mSrecGrammar.destroy(); mSrecGrammar = null; // Attempt to load new grammar from cached copy try { mGrammar = cached; mSrecGrammar = mSrec.new Grammar(cached.getPath()); mSrecGrammar.setupRecognizer(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
/** * Stops the recognition thread and destroys the recognizer. You may not call any methods on the * object after calling this method. */ public void shutdown() { stop(); mSrecGrammar.destroy(); mSrec.destroy(); }