我正在为使用Sphinx 4的Java应用程序开发语音识别。我想要对ANDroid进行语音识别。请帮助我:)
答案 0 :(得分:0)
//declearation
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
TextToSpeech talker;
//onCreate
Button speakButton=new Button(this);
talker = new TextToSpeech(this, 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");
}
//methods
/**
* 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) {
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
String device = "Bedroom";
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);
}
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();
}