Android:使用Speech To Text API进行语音到文本转换

Android有一个非常酷的特性很多开发者都还不知道。Any.DO之类应用的语音到文本转换功能很有创意。在现在Siri的世界里,语音指令是极其重要的。Android原生提供Speech To Text功能,为什么不把它用在我们的程序中!

我将会展示如何在程序中使用Android的Speech To Text API,现在开始写我们的demo程序。

Demo程序
这个程序很简单。他有一个Mic符号按钮。点击之后我们触发Android的Speech To Text意图(Intent)显示一个对话框来接收语音输入。输入的语音然后会被转换成文本并显示到一个text view中。

第一步:在Eclipse中创建基本的Android项目
在Eclipse中创建一个Hello World Android项目。打开  New > Project > Android Project,项目名填  SpeechToTextDemo,选择Android运行时2.1或sdk7。我给定了包名: net.viralpatel.android.speechtotextdemo

做完上面的步骤,你就有了一个基本的Android Hello World程序

第二步:更改布局
在我们的demo中布局很简单。只有一个图像按钮来触发Speech to Text API和一个TextView来显示从语音转换过来的文本。

打开layout/main.xml并替换为下面的内容:
File: res/layout/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >
 
    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android :drawable/ic_btn_speak_now" />
 
    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</LinearLayout>


第三步:触发Speech to Text API的Android Java代码
打开SpeechToTextDemoActivity 类并替换为下面的代码:
File: SpeechToTextDemoActivity.java
package net.viralpatel.android.speechtotextdemo;
 
import java.util.ArrayList;
 
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    protected static final int RESULT_SPEECH = 1;
 
    private ImageButton btnSpeak;
    private TextView txtText;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        txtText = (TextView) findViewById(R.id.txtText);
 
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
 
        btnSpeak.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
 
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
 
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
 
                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {
 
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
 
                txtText.setText(text.get(0));
            }
            break;
        }
 
        }
    }
}

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异常会被抛出。在上面的例子中,我们捕获了这个异常并使用Toast显示了一个提示信息“Opps! Your device doesn’t support Speech to Text”。

Android应用程序的屏幕截图
到这里就结束了! 在Android模拟器或真实设备上执行应用程序,将会看到下面的输出。
 
 
 
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值