当前位置:   article > 正文

安卓 —— 图灵机器人+讯飞语音设计实现_android 科大讯飞语音+图灵机器人

android 科大讯飞语音+图灵机器人

前言:

  本文主要介绍一下之前学习的安卓平台下 “图灵机器人的设计”,希望能给爱学习的你到来更多的启发和兴趣。当然,随着时间的推延,技术的优化和进步,难免出现新技术的更迭,所以要经常充电学习...

  安卓开发:android4.2-5.0 


【注:2017-12-12

  今天在同事手机上安装了一下试试,发现红米手机可支持,并且没有使用讯飞输入法也可以完成。

  毕竟代码编辑久远,当初的代码是在 android4.2 - 5.0 版本下开发的,如今的安卓版本更新换代快,终究会出现兼容问题,此外两年多没有碰安卓代码了,可能很难给以参考的伙伴以有价值的建议,希望多多进步咯 ...


一.前期准备:

  1.代码编写之前,在此提供 前辈大牛的视频讲解其中涉及到了图灵账号的注册和效果实现

  2.其中注册网址为 图灵机器人官网 ,具体操作可看官方文档和之前的视频链接

  3.在此补充一个感觉很好的 参考博文 ,编写之前也参考了他的很多,主要还是学习众家所长嘛

  4.代码使用了讯飞语音,个人认为如果使用的讯飞输入法,同时下载了其语音,在编辑的同时即可使用,而此代码表示需要在联网状态进行语音的输入转化。

二.代码编写:

①. 权限设置

  1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  2. <!-- 讯飞语音权限开始 -->
  3. <uses-permission android:name="android.permission.INTERNET" />
  4. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  5. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  6. <uses-permission android:name="android.permission.RECORD_AUDIO" />
  7. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  8. <!-- 讯飞语音权限结束 -->

②. 项目展开状况如下所示

注意对应的jar包使用,之后会附上源码下载地址作为参考

③. 布局文件

(1). /HoMotou/res/layout/motou_view.xml 源码

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:background="@drawable/bg4"
  5. android:layout_height="match_parent" >
  6. <include
  7. android:id="@+id/include_top_motou"
  8. layout="@layout/top_motou" />
  9. <RelativeLayout
  10. android:id="@+id/id_ly_bottom"
  11. android:layout_width="fill_parent"
  12. android:layout_height="55dp"
  13. android:layout_alignParentBottom="true"
  14. android:background="@drawable/bottom_bar" >
  15. <Button
  16. android:id="@+id/id_send_msg"
  17. android:layout_width="60dp"
  18. android:layout_height="40dp"
  19. android:layout_marginRight="3dp"
  20. android:layout_alignParentRight="true"
  21. android:layout_centerVertical="true"
  22. android:background="@drawable/send_btn_bg"
  23. android:text="发送" />
  24. <Button
  25. android:layout_marginLeft="3dp"
  26. android:id="@+id/iv_voice"
  27. android:layout_width="40dp"
  28. android:layout_height="40dp"
  29. android:layout_alignParentLeft="true"
  30. android:layout_centerVertical="true"
  31. android:background="@drawable/voice"
  32. android:text="" />
  33. <EditText
  34. android:id="@+id/id_input_msg"
  35. android:layout_width="fill_parent"
  36. android:layout_height="40dp"
  37. android:layout_centerVertical="true"
  38. android:layout_marginLeft="10dp"
  39. android:layout_marginRight="10dp"
  40. android:layout_toRightOf="@id/iv_voice"
  41. android:layout_toLeftOf="@id/id_send_msg"
  42. android:background="@drawable/login_edit_normal"
  43. android:textSize="18sp" />
  44. </RelativeLayout>
  45. <ListView
  46. android:id="@+id/id_listview_msgs"
  47. android:layout_width="match_parent"
  48. android:layout_height="match_parent"
  49. android:layout_marginLeft="7dp"
  50. android:layout_marginRight="7dp"
  51. android:layout_above="@id/id_ly_bottom"
  52. android:layout_below="@id/include_top_motou"
  53. android:divider="@null"
  54. android:dividerHeight="5dp" >
  55. </ListView>
  56. </RelativeLayout>


(2). /HoMotou/res/layout/item_from_msg.xml 源码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:layout_weight="1"
  8. android:id="@+id/id_form_msg_date"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:layout_gravity="center"
  12. android:text="@string/timeDemo"
  13. android:textColor="@color/darkGreen"
  14. android:textSize="12sp" />
  15. <LinearLayout
  16. android:layout_weight="2"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content"
  19. android:orientation="horizontal" >
  20. <ImageView
  21. android:layout_width="49dp"
  22. android:layout_height="49dp"
  23. android:src="@drawable/sgc" />
  24. <TextView
  25. android:id="@+id/id_from_msg_info"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:background="@drawable/chatfrom_bg_normal"
  29. android:gravity="center_vertical"
  30. android:textSize="17sp"
  31. android:textColor="@color/dark_hese"
  32. android:text="@string/hello" />
  33. </LinearLayout>
  34. </LinearLayout>


(3). /HoMotou/res/layout/item_to_msg.xml 源码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:gravity="right"
  6. android:orientation="vertical" >
  7. <TextView
  8. android:id="@+id/id_to_msg_date"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:layout_gravity="center"
  12. android:text="@string/timeDemo"
  13. android:textColor="@color/darkGreen"
  14. android:textSize="12sp" />
  15. <LinearLayout
  16. android:layout_width="match_parent"
  17. android:layout_height="wrap_content"
  18. android:orientation="horizontal" >
  19. <LinearLayout
  20. android:layout_weight="5"
  21. android:gravity="right"
  22. android:layout_width="match_parent"
  23. android:layout_height="wrap_content"
  24. android:orientation="horizontal" >
  25. <TextView
  26. android:id="@+id/id_to_msg_info"
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content"
  29. android:layout_marginLeft="3dp"
  30. android:background="@drawable/chatto_bg_normal"
  31. android:text="dfgs发过"
  32. android:textColor="@color/dark_hese"
  33. android:textSize="17sp" />
  34. </LinearLayout>
  35. <ImageView
  36. android:layout_weight="1"
  37. android:layout_width="49dp"
  38. android:layout_height="49dp"
  39. android:src="@drawable/yoo" />
  40. </LinearLayout>
  41. </LinearLayout>

(4)./HoMotou/res/layout/top_motou.xml 源码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:background="#eee"
  6. android:orientation="vertical" >
  7. <LinearLayout
  8. android:layout_width="match_parent"
  9. android:layout_height="46dp"
  10. android:gravity="center"
  11. android:background="#ebebeb"
  12. android:orientation="horizontal" >
  13. <TextView
  14. android:layout_weight="3"
  15. android:paddingLeft="3dp"
  16. android:id="@+id/tv_back"
  17. android:textColor="#C0C0C0"
  18. android:layout_width="match_parent"
  19. android:layout_height="match_parent"
  20. android:gravity="center" />
  21. <TextView
  22. android:layout_weight="2"
  23. android:layout_width="match_parent"
  24. android:layout_height="match_parent"
  25. android:text="@string/top_motou"
  26. android:gravity="center"
  27. android:textSize="18sp"
  28. android:textColor="#008000" />
  29. <TextView
  30. android:layout_weight="3"
  31. android:paddingLeft="3dp"
  32. android:id="@+id/tv_2"
  33. android:textColor="#C0C0C0"
  34. android:layout_width="match_parent"
  35. android:layout_height="match_parent"
  36. android:gravity="center" />
  37. </LinearLayout>
  38. <ImageView
  39. android:id="@+id/id_iv_tabline"
  40. android:layout_width="match_parent"
  41. android:layout_height="1dp"
  42. android:background="@drawable/tabline" />
  43. </LinearLayout>

④. 适配器设计代码如下

(/HoMotou/src/com/mo/adapter/ChatMessageAdapter.java)

  1. package com.mo.adapter;
  2. import java.text.SimpleDateFormat;
  3. import java.util.List;
  4. import com.mo.bean.ChatMessage;
  5. import com.mo.bean.ChatMessage.Type;
  6. import com.mo.hoo.R;
  7. import android.content.Context;
  8. import android.view.LayoutInflater;
  9. import android.view.View;
  10. import android.view.ViewGroup;
  11. import android.widget.BaseAdapter;
  12. import android.widget.TextView;
  13. public class ChatMessageAdapter extends BaseAdapter
  14. {
  15. private LayoutInflater mInflater;
  16. private List<ChatMessage> mDatas;
  17. public ChatMessageAdapter(Context context, List<ChatMessage> mDatas)
  18. {
  19. mInflater = LayoutInflater.from(context);
  20. this.mDatas = mDatas;
  21. }
  22. @Override
  23. public int getCount()
  24. {
  25. return mDatas.size();
  26. }
  27. @Override
  28. public Object getItem(int position)
  29. {
  30. return mDatas.get(position);
  31. }
  32. @Override
  33. public long getItemId(int position)
  34. {
  35. return position;
  36. }
  37. @Override
  38. public int getItemViewType(int position)
  39. {
  40. ChatMessage chatMessage = mDatas.get(position);
  41. if (chatMessage.getType() == Type.INCOMING)
  42. {
  43. return 0;
  44. }
  45. return 1;
  46. }
  47. @Override
  48. public int getViewTypeCount()
  49. {
  50. return 2;
  51. }
  52. @Override
  53. public View getView(int position, View convertView, ViewGroup parent)
  54. {
  55. ChatMessage chatMessage = mDatas.get(position);
  56. ViewHolder viewHolder = null;
  57. if (convertView == null)
  58. {
  59. // 通过ItemType设置不同的布局
  60. if (getItemViewType(position) == 0)
  61. {
  62. convertView = mInflater.inflate(R.layout.item_from_msg, parent,
  63. false);
  64. viewHolder = new ViewHolder();
  65. viewHolder.mDate = (TextView) convertView
  66. .findViewById(R.id.id_form_msg_date);
  67. viewHolder.mMsg = (TextView) convertView
  68. .findViewById(R.id.id_from_msg_info);
  69. } else
  70. {
  71. convertView = mInflater.inflate(R.layout.item_to_msg, parent,
  72. false);
  73. viewHolder = new ViewHolder();
  74. viewHolder.mDate = (TextView) convertView
  75. .findViewById(R.id.id_to_msg_date);
  76. viewHolder.mMsg = (TextView) convertView
  77. .findViewById(R.id.id_to_msg_info);
  78. }
  79. convertView.setTag(viewHolder);
  80. } else
  81. {
  82. viewHolder = (ViewHolder) convertView.getTag();
  83. }
  84. // 设置数据
  85. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  86. viewHolder.mDate.setText(df.format(chatMessage.getDate()));
  87. viewHolder.mMsg.setText(chatMessage.getMsg());
  88. return convertView;
  89. }
  90. private final class ViewHolder
  91. {
  92. TextView mDate;
  93. TextView mMsg;
  94. }
  95. }

⑤. 实现消息发送与接收的工具类设计

(/HoMotou/src/com/mo/util/HttpUtils.java)

  1. package com.mo.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.URLEncoder;
  9. import java.util.Date;
  10. import com.google.gson.Gson;
  11. import com.mo.bean.ChatMessage;
  12. import com.mo.bean.ChatMessage.Type;
  13. import com.mo.bean.Result;
  14. public class HttpUtils
  15. {
  16. private static final String URL = "http://www.tuling123.com/openapi/api";
  17. //"请自行申请apikey"
  18. private static final String API_KEY = "0905b3be27b638a58362d682529e2a3b";
  19. /**
  20. * 发送一个消息,得到返回的消息
  21. * @param msg
  22. * @return
  23. */
  24. public static ChatMessage sendMessage(String msg)
  25. {
  26. ChatMessage chatMessage = new ChatMessage();
  27. String jsonRes = doGet(msg);
  28. Gson gson = new Gson();
  29. Result result = null;
  30. try
  31. {
  32. result = gson.fromJson(jsonRes, Result.class);
  33. chatMessage.setMsg(result.getText());
  34. } catch (Exception e)
  35. {
  36. chatMessage.setMsg("服务器繁忙,请稍候再试");
  37. }
  38. chatMessage.setDate(new Date());
  39. chatMessage.setType(Type.INCOMING);
  40. return chatMessage;
  41. }
  42. public static String doGet(String msg)
  43. {
  44. String result = "";
  45. String url = setParams(msg);
  46. ByteArrayOutputStream baos = null;
  47. InputStream is = null;
  48. try
  49. {
  50. java.net.URL urlNet = new java.net.URL(url);
  51. HttpURLConnection conn = (HttpURLConnection) urlNet
  52. .openConnection();
  53. conn.setReadTimeout(5 * 1000);
  54. conn.setConnectTimeout(5 * 1000);
  55. conn.setRequestMethod("GET");
  56. is = conn.getInputStream();
  57. int len = -1;
  58. byte[] buf = new byte[128];
  59. baos = new ByteArrayOutputStream();
  60. while ((len = is.read(buf)) != -1)
  61. {
  62. baos.write(buf, 0, len);
  63. }
  64. baos.flush();
  65. result = new String(baos.toByteArray());
  66. } catch (MalformedURLException e)
  67. {
  68. e.printStackTrace();
  69. } catch (Exception e)
  70. {
  71. e.printStackTrace();
  72. } finally
  73. {
  74. try
  75. {
  76. if (baos != null)
  77. baos.close();
  78. } catch (IOException e)
  79. {
  80. e.printStackTrace();
  81. }
  82. try
  83. {
  84. if (is != null)
  85. {
  86. is.close();
  87. }
  88. } catch (IOException e)
  89. {
  90. e.printStackTrace();
  91. }
  92. }
  93. return result;
  94. }
  95. private static String setParams(String msg)
  96. {
  97. String url = "";
  98. try
  99. {
  100. url = URL + "?key=" + API_KEY + "&info="
  101. + URLEncoder.encode(msg, "UTF-8");
  102. } catch (UnsupportedEncodingException e)
  103. {
  104. e.printStackTrace();
  105. }
  106. return url;
  107. }
  108. }

⑥. 主体Activity设计

(/HoMotou/src/com/mo/hoo/MuTouActivity.java)

  1. package com.mo.hoo;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;
  5. import com.mo.adapter.ChatMessageAdapter;
  6. import com.mo.bean.ChatMessage;
  7. import com.mo.bean.ChatMessage.Type;
  8. import com.mo.util.HttpUtils;
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.os.Handler;
  12. import android.os.Message;
  13. import android.text.TextUtils;
  14. import android.util.Log;
  15. import android.view.View;
  16. import android.view.Window;
  17. import android.view.View.OnClickListener;
  18. import android.widget.Button;
  19. import android.widget.EditText;
  20. import android.widget.ImageView;
  21. import android.widget.ListView;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24. public class MuTouActivity extends Activity {
  25. public static String toMsg="";
  26. private ListView mMsgs;
  27. private ChatMessageAdapter mAdapter;
  28. private List<ChatMessage> mDatas;
  29. private TextView tv_back;
  30. public static EditText mInputMsg;
  31. private Button mSendMsg;
  32. private Button iv_voice;
  33. private Handler mHandler = new Handler()
  34. {
  35. public void handleMessage(android.os.Message msg)
  36. {
  37. // 等待接收,子线程完成数据的返回
  38. ChatMessage fromMessge = (ChatMessage) msg.obj;
  39. mDatas.add(fromMessge);
  40. mAdapter.notifyDataSetChanged();
  41. mMsgs.setSelection(mDatas.size()-1);
  42. };
  43. };
  44. @Override
  45. protected void onCreate(Bundle savedInstanceState)
  46. {
  47. super.onCreate(savedInstanceState);
  48. overridePendingTransition(R.anim.push_right_in,R.anim.hold);
  49. requestWindowFeature(Window.FEATURE_NO_TITLE);
  50. setContentView(R.layout.motou_view);
  51. initView();
  52. initDatas();
  53. // 初始化事件
  54. initListener();
  55. }
  56. private void initListener()
  57. {
  58. mSendMsg.setOnClickListener(new OnClickListener()
  59. {
  60. @Override
  61. public void onClick(View v)
  62. {
  63. toMsg = mInputMsg.getText().toString();
  64. if (TextUtils.isEmpty(toMsg))
  65. {
  66. Toast.makeText(MuTouActivity.this, "发送消息不能为空!",
  67. Toast.LENGTH_SHORT).show();
  68. return;
  69. }
  70. ChatMessage toMessage = new ChatMessage();
  71. toMessage.setDate(new Date());
  72. toMessage.setMsg(toMsg);
  73. toMessage.setType(Type.OUTCOMING);
  74. mDatas.add(toMessage);
  75. mAdapter.notifyDataSetChanged();
  76. mMsgs.setSelection(mDatas.size()-1);
  77. mInputMsg.setText("");
  78. new Thread()
  79. {
  80. public void run()
  81. {
  82. ChatMessage fromMessage = HttpUtils.sendMessage(toMsg);
  83. Message m = Message.obtain();
  84. m.obj = fromMessage;
  85. mHandler.sendMessage(m);
  86. };
  87. }.start();
  88. }
  89. });
  90. tv_back.setOnClickListener(new OnClickListener() {
  91. @Override
  92. public void onClick(View v) {
  93. finish();
  94. overridePendingTransition(R.anim.hold,R.anim.push_right_out);
  95. }
  96. });
  97. }
  98. private void initDatas()
  99. {
  100. mDatas = new ArrayList<ChatMessage>();
  101. mDatas.add(new ChatMessage("笨蛋,找我干嘛啊?", Type.INCOMING, new Date()));
  102. mAdapter = new ChatMessageAdapter(this, mDatas);
  103. mMsgs.setAdapter(mAdapter);
  104. iv_voice.setOnClickListener(new OnClickListener() {
  105. @Override
  106. public void onClick(View v) {
  107. // 初始化,再加载
  108. //MyRecognizerDialogLister.text="";
  109. VoiceToWord voice = new VoiceToWord(MuTouActivity.this,"534e3fe2");
  110. voice.GetWordFromVoice();
  111. }
  112. });
  113. }
  114. private void initView()
  115. {
  116. mMsgs = (ListView) findViewById(R.id.id_listview_msgs);
  117. mInputMsg = (EditText) findViewById(R.id.id_input_msg);
  118. mSendMsg = (Button) findViewById(R.id.id_send_msg);
  119. tv_back=(TextView) findViewById(R.id.tv_back);
  120. iv_voice=(Button) findViewById(R.id.iv_voice);
  121. }
  122. }

⑦. 用于实现讯飞语音输入的JSON解析类

  1. package com.mo.hoo;
  2. import org.json.JSONArray;
  3. import org.json.JSONObject;
  4. import org.json.JSONTokener;
  5. import android.text.TextUtils;
  6. //import com.iflytek.speech.ErrorCode;
  7. //import com.iflytek.speech.SpeechError;
  8. /**
  9. * 对云端返回的Json结果进行解析
  10. * @author iFlytek
  11. * @since 20131211
  12. */
  13. public class JsonParser {
  14. /**
  15. * 听写结果的Json格式解析
  16. * @param json
  17. * @return
  18. */
  19. private static boolean isTag;
  20. public static String parseIatResult(String json) {
  21. if(TextUtils.isEmpty(json))
  22. return "";
  23. StringBuffer ret = new StringBuffer();
  24. try {
  25. JSONTokener tokener = new JSONTokener(json);
  26. JSONObject joResult = new JSONObject(tokener);
  27. JSONArray words = joResult.getJSONArray("ws");
  28. for (int i = 0; i < words.length(); i++) {
  29. // 听写结果词,默认使用第一个结果
  30. JSONArray items = words.getJSONObject(i).getJSONArray("cw");
  31. JSONObject obj = items.getJSONObject(0);
  32. ret.append(obj.getString("w"));
  33. // 如果需要多候选结果,解析数组其他字段
  34. // for(int j = 0; j < items.length(); j++)
  35. // {
  36. // JSONObject obj = items.getJSONObject(j);
  37. // ret.append(obj.getString("w"));
  38. // }
  39. }
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. return ret.toString();
  44. }
  45. /**
  46. * 识别结果的Json格式解析
  47. * @param json
  48. * @return
  49. */
  50. public static String parseGrammarResult(String json) {
  51. StringBuffer ret = new StringBuffer();
  52. try {
  53. JSONTokener tokener = new JSONTokener(json);
  54. JSONObject joResult = new JSONObject(tokener);
  55. JSONArray words = joResult.getJSONArray("ws");
  56. for (int i = 0; i < words.length(); i++) {
  57. JSONArray items = words.getJSONObject(i).getJSONArray("cw");
  58. for(int j = 0; j < items.length(); j++)
  59. {
  60. JSONObject obj = items.getJSONObject(j);
  61. if(obj.getString("w").contains("nomatch"))
  62. {
  63. ret.append("没有匹配结果.");
  64. return ret.toString();
  65. }
  66. ret.append("【结果】" + obj.getString("w"));
  67. ret.append("【置信度】" + obj.getInt("sc"));
  68. ret.append("\n");
  69. }
  70. }
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. ret.append("没有匹配结果.");
  74. }
  75. return ret.toString();
  76. }
  77. /**
  78. * 语义结果的Json格式解析
  79. * @param json
  80. * @return
  81. */
  82. public static String parseUnderstandResult(String json) {
  83. StringBuffer ret = new StringBuffer();
  84. try {
  85. JSONTokener tokener = new JSONTokener(json);
  86. JSONObject joResult = new JSONObject(tokener);
  87. ret.append("【应答码】" + joResult.getString("rc") + "\n");
  88. ret.append("【转写结果】" + joResult.getString("text") + "\n");
  89. ret.append("【服务名称】" + joResult.getString("service") + "\n");
  90. ret.append("【操作名称】" + joResult.getString("operation") + "\n");
  91. ret.append("【完整结果】" + json);
  92. } catch (Exception e) {
  93. e.printStackTrace();
  94. ret.append("没有匹配结果.");
  95. }
  96. return ret.toString();
  97. }
  98. }

⑧. 语音转化为文字的实现类

  1. package com.mo.hoo;
  2. import com.iflytek.cloud.speech.SpeechConstant;
  3. import com.iflytek.cloud.speech.SpeechError;
  4. import com.iflytek.cloud.speech.SpeechListener;
  5. import com.iflytek.cloud.speech.SpeechRecognizer;
  6. import com.iflytek.cloud.speech.SpeechUser;
  7. import com.iflytek.cloud.ui.RecognizerDialog;
  8. import com.iflytek.cloud.ui.RecognizerDialogListener;
  9. import android.app.Activity;
  10. import android.content.Context;
  11. import android.content.SharedPreferences;
  12. import android.os.Bundle;
  13. import android.text.TextUtils;
  14. import android.widget.Toast;
  15. public class VoiceToWord extends Activity{
  16. private Context context;
  17. private Toast mToast;
  18. //识别窗口
  19. private RecognizerDialog iatDialog;
  20. //识别对象
  21. private SpeechRecognizer iatRecognizer;
  22. //缓存,保存当前的引擎参数到下一次启动应用程序使用.
  23. private SharedPreferences mSharedPreferences;
  24. private RecognizerDialogListener recognizerDialogListener = null;
  25. public VoiceToWord(Context context,String APP_ID) {
  26. // TODO Auto-generated constructor stub
  27. //用户登录
  28. this.context = context;
  29. SpeechUser.getUser().login(context, null, null
  30. , "appid=" + APP_ID, listener);
  31. //初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
  32. iatDialog =new RecognizerDialog(context);
  33. mToast = Toast.makeText(context, "", Toast.LENGTH_LONG);
  34. //初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
  35. iatDialog =new RecognizerDialog(context);
  36. //初始化缓存对象.
  37. mSharedPreferences = context.getSharedPreferences(context.getPackageName(),MODE_PRIVATE);
  38. }
  39. public VoiceToWord(Context context,String APP_ID,RecognizerDialogListener recognizerDialogListener)
  40. {
  41. this.context = context;
  42. SpeechUser.getUser().login(context, null, null
  43. , "appid=" + APP_ID, listener);
  44. //初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
  45. iatDialog =new RecognizerDialog(context);
  46. mToast = Toast.makeText(context, "", Toast.LENGTH_LONG);
  47. //初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
  48. iatDialog =new RecognizerDialog(context);
  49. //初始化缓存对象.
  50. mSharedPreferences = context.getSharedPreferences(context.getPackageName(),MODE_PRIVATE);
  51. this.recognizerDialogListener = recognizerDialogListener;
  52. }
  53. public void GetWordFromVoice()
  54. {
  55. boolean isShowDialog = mSharedPreferences.getBoolean("iat_show",true);
  56. if (isShowDialog) {
  57. //显示语音听写Dialog.
  58. showIatDialog();
  59. } else {
  60. if(null == iatRecognizer) {
  61. iatRecognizer=SpeechRecognizer.createRecognizer(this);
  62. }
  63. if(iatRecognizer.isListening()) {
  64. iatRecognizer.stopListening();
  65. // ((Button) findViewById(android.R.id.button1)).setEnabled(false);
  66. } else {
  67. }
  68. }
  69. }
  70. private void showTip1(String str)
  71. {
  72. if(!TextUtils.isEmpty(str))
  73. {
  74. mToast.setText(str);
  75. mToast.show();
  76. }
  77. }
  78. /**
  79. * 显示听写对话框.
  80. * @param
  81. */
  82. public void showIatDialog()
  83. {
  84. if(null == iatDialog) {
  85. //初始化听写Dialog
  86. iatDialog =new RecognizerDialog(this);
  87. }
  88. //获取引擎参数
  89. String engine = mSharedPreferences.getString(
  90. "iat_engine",
  91. "iat");
  92. //清空Grammar_ID,防止识别后进行听写时Grammar_ID的干扰
  93. iatDialog.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
  94. //设置听写Dialog的引擎
  95. iatDialog.setParameter(SpeechConstant.DOMAIN, engine);
  96. //设置采样率参数,支持8K和16K
  97. String rate = mSharedPreferences.getString(
  98. "sf",
  99. "sf");
  100. if(rate.equals("rate8k"))
  101. {
  102. iatDialog.setParameter(SpeechConstant.SAMPLE_RATE, "8000");
  103. }
  104. else
  105. {
  106. iatDialog.setParameter(SpeechConstant.SAMPLE_RATE, "16000");
  107. }
  108. if(recognizerDialogListener == null)
  109. {
  110. getRecognizerDialogListener();
  111. }
  112. //显示听写对话框
  113. iatDialog.setListener(recognizerDialogListener);
  114. iatDialog.show();
  115. }
  116. private void getRecognizerDialogListener()
  117. {
  118. /**
  119. * 识别回调监听器
  120. */
  121. recognizerDialogListener=new MyRecognizerDialogLister(context);
  122. }
  123. /**
  124. * 用户登录回调监听器.
  125. */
  126. private SpeechListener listener = new SpeechListener()
  127. {
  128. @Override
  129. public void onData(byte[] arg0) {
  130. }
  131. @Override
  132. public void onCompleted(SpeechError error) {
  133. if(error != null) {
  134. System.out.println("user login success");
  135. }
  136. }
  137. @Override
  138. public void onEvent(int arg0, Bundle arg1) {
  139. }
  140. };
  141. }

⑨. 项目运行截图



⑩. 附录

源码下载,仅供参考 >>>


【声明】如有转载,请注明信息来源,欢迎学习,指点 ...

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/225408
推荐阅读
相关标签
  

闽ICP备14008679号