设为首页 加入收藏

TOP

利用Android传感器完成 Android语音输入
2014-11-24 01:19:58 来源: 作者: 【 】 浏览:2
Tags:利用 Android 传感器 完成 语音 输入

1、先晒晒效果图:




2、manifest 文件访问网络配置:


3、layout配置文件代码:


< xml version="1.0" encoding="utf-8" >
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >


android:id="@+id/txtVoiceInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/sensor_voice_input_lb_title" >




android:id="@+id/btnStartVoiceInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sensor_voice_input_btn_startinput" />



4、Java代码:


private Button btnStartVoiceInput;

private int InputResultCode = 1;
private EditText txtVoiceInput;

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

//开始语音输入按钮绑定
txtVoiceInput = (EditText)findViewById(R.id.txtVoiceInput);
btnStartVoiceInput = (Button)findViewById(R.id.btnStartVoiceInput);
btnStartVoiceInput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//调用系统传感器语音输入Api
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//必须输入项语言模式
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

try {
startActivityForResult(intent, InputResultCode);
txtVoiceInput.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"抱歉您的系统不支持语音识别输入。",
Toast.LENGTH_LONG);
t.show();
}
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == InputResultCode && resultCode == RESULT_OK && data != null) {
//获取解析的结果
ArrayList voiceList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtVoiceInput.setText(voiceList.get(0));
}
}


Android Speech to text Android API的核心是包 android.speech和类 android.speech.RecognizerIntent。我们触发一个意图(android.speech.RecognizerIntent)显示对话框来识别语音输入,这个Activity转换语音为文本并把结果传回我们正在调用的Activity。当我们调用android.speech.RecognizerIntent意图时,必须使用 startActivityForResult()来接听文本结果。


注意在上面的代码中我们是怎样创建并触发意图intent android.speech.RecognizerIntent的,同时使用.putExtra()方法添加了一个参数。调用RecognizerIntent时,必须提供RecognizerIntent.EXTRA_LANGUAGE_MODE,在这里我们设置为 en-US。


由于我们的RecognizerIntent通过startActivityForResult()触发,我们重写了 onActivityResult(int requestCode, int resultCode, Intent data)方法来处理结果数据。RecognizerIntent会把语音转换为文本并把结果通过键RecognizerIntent.EXTRA_RESULTS作为ArrayList传回来。只有RESULT_OK返回时才会出现。我们只需要使用 txtText.setText()把从结果中拿到的文本设置到text view texText中。


在这里值得注意的一件事是在不支持speech to text API的设备/Android版本中应该怎样处理。在这种情况下,当我们视图启动Activity时ActivityNotFoundException异常会被抛出。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java1.5后的多线程框架 下一篇Socket网络编程-Mina 实例

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: