Add voice search to native action bar in titanium app

Posted By : Sapna Sharma | 24-Feb-2015

Utterance (Titanium module) lets you use speech to text in your Titanium apps. In order to use it into your Titanium program import it using require

var utterance = require('bencoding.utterance');

The SpeechToText proxy is available on Android and provides Speech to Text capabilities using your device’s native platform speech recognizer. When the startSpeechToText method is called, a microphone dialog will appear and listen for input from the user.  When the user stops speaking, Android’s speech recognizer will convert what was said into one or more text phrases.  If Android is not fully able to match was is said, the speech recognizer will provide a list of options in the order it feels is the best match.


Here is the code -

 

 var win = Ti.UI.createWindow({ 
 backgroundColor: 'blue', 
 fullscreen: false,
});

if (Ti.Platform.name == 'android'){
   win.activity.onCreateOptionsMenu = function(e) {
      var menu = e.menu;
      var menuItem = menu.add({
      icon : "/images/icons/voice_search.jpeg",
      showAsAction : Ti.Android.SHOW_AS_ACTION_IF_ROOM | Ti.Android.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW,
  });
  menuItem.addEventListener("click", function(e) {
      doSearch();
  });
 }
}

function doSearch() {
		var utterance = require('bencoding.utterance'),
		    speechToText = utterance.createSpeechToText();
		speechToText.startSpeechToText({
			promptText : "Say something interesting",
			maxResults : 10
		});

		speechToText.addEventListener('started', function(e) {
			Ti.API.info(JSON.stringify(e));
		});

		speechToText.addEventListener('completed', function(e) {
			Ti.API.info(JSON.stringify(e));
			if (e.success && (e.wordCount > 0)) {
				alert("Speech Recognized " + e.wordCount + " matches found: " + JSON.stringify(e.words));
			} else {
				alert("Unable to recognize your speech");
			}
		});
	}

 

Thanks

About Author

Author Image
Sapna Sharma

Sapna is a bright Android Apps developer using Titanium framework. Sapna likes music and helping needy people.

Request for Proposal

Name is required

Comment is required

Sending message..