当前位置:   article > 正文

智能聊天机器人的实现(语音引入第三方科大讯飞)_synthesizerplayer setvoicename

synthesizerplayer setvoicename

  1. /**
  2. * MainActivity
  3. */
  4. package com.example.moo;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import android.app.Activity;
  9. import android.os.Bundle;
  10. import android.os.Handler;
  11. import android.os.Message;
  12. import android.text.TextUtils;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.view.Window;
  17. import android.widget.Button;
  18. import android.widget.EditText;
  19. import android.widget.ListView;
  20. import android.widget.Toast;
  21. import com.example.bean.ChatMessage;
  22. import com.example.bean.ChatMessage.Type;
  23. import com.example.utils.HttpUtils;
  24. import com.iflytek.speech.RecognizerResult;
  25. import com.iflytek.speech.SpeechError;
  26. import com.iflytek.speech.SynthesizerPlayer;
  27. import com.iflytek.speech.SynthesizerPlayerListener;
  28. import com.iflytek.ui.RecognizerDialog;
  29. import com.iflytek.ui.RecognizerDialogListener;
  30. public class MainActivity extends Activity implements OnClickListener {
  31. protected static final String tag = "MainActivity";
  32. private ListView mMsgs;
  33. private ChatMessageAdapter mAdapter;
  34. private List<ChatMessage> mDatas;
  35. private EditText mInputMsg;
  36. private Button mSendMsg;
  37. private Button mBtnVoice;
  38. private boolean isVoice;
  39. private Handler mHandler = new Handler() {
  40. public void handleMessage(android.os.Message msg) {
  41. // 等待接收,子线程完成数据返回
  42. ChatMessage fromMessage = (ChatMessage) msg.obj;
  43. mDatas.add(fromMessage);
  44. scrollMsgToBottom();// listView滚动到底部
  45. mAdapter.notifyDataSetChanged();
  46. if (isVoice) {
  47. // 来自语音的话要识别并且说话
  48. initSynthesizerplayer(fromMessage.getMsg());
  49. }
  50. };
  51. };
  52. @Override
  53. protected void onCreate(Bundle savedInstanceState) {
  54. super.onCreate(savedInstanceState);
  55. requestWindowFeature(Window.FEATURE_NO_TITLE);
  56. setContentView(R.layout.activity_main);
  57. initView();
  58. initData();
  59. // 初始化事件
  60. initListener();
  61. }
  62. private void initView() {
  63. mMsgs = (ListView) findViewById(R.id.id_listview_msgs);
  64. mInputMsg = (EditText) findViewById(R.id.id_input_msg);
  65. mSendMsg = (Button) findViewById(R.id.sent_msg);
  66. mBtnVoice = (Button) findViewById(R.id.btn_voice);
  67. }
  68. private void initData() {
  69. mDatas = new ArrayList<ChatMessage>();
  70. mDatas.add(new ChatMessage("您好,小慕为您服务", new Date(), Type.INCOMING));
  71. mAdapter = new ChatMessageAdapter(this, mDatas);
  72. mMsgs.setAdapter(mAdapter);
  73. }
  74. private void initListener() {
  75. mSendMsg.setOnClickListener(this);
  76. mBtnVoice.setOnClickListener(this);
  77. }
  78. private String toMsg = "";
  79. @Override
  80. public void onClick(View v) {
  81. switch (v.getId()) {
  82. case R.id.sent_msg:
  83. isVoice = false;
  84. toMsg = mInputMsg.getText().toString();
  85. sendMessage(toMsg);
  86. break;
  87. case R.id.btn_voice:
  88. isVoice = true;
  89. initRecognizerDialog();
  90. break;
  91. }
  92. }
  93. /**
  94. * 发送消息
  95. *
  96. * @param toMsg
  97. */
  98. private void sendMessage(final String toMsg) {
  99. if (TextUtils.isEmpty(toMsg)) {
  100. Toast.makeText(MainActivity.this, "消息不能为空!", Toast.LENGTH_SHORT)
  101. .show();
  102. return;
  103. }
  104. ChatMessage toMessage = new ChatMessage();
  105. toMessage.setDate(new Date());
  106. toMessage.setMsg(toMsg);
  107. toMessage.setType(Type.OUTCOMING);
  108. mDatas.add(toMessage);
  109. mAdapter.notifyDataSetChanged();
  110. mInputMsg.setText("");
  111. new Thread() {
  112. public void run() {
  113. ChatMessage fromMeString = HttpUtils.sendMessage(toMsg);
  114. Message m = Message.obtain();
  115. m.obj = fromMeString;
  116. mHandler.sendMessage(m);
  117. };
  118. }.start();
  119. }
  120. // 准备说话
  121. private void initRecognizerDialog() {
  122. RecognizerDialog recognizerDialog = new RecognizerDialog(this,
  123. "appid=5212ef0a");
  124. toMsg = "";
  125. recognizerDialog.setEngine("sms", null, null);
  126. recognizerDialog.setListener(dialogListener);
  127. recognizerDialog.show();
  128. }
  129. RecognizerDialogListener dialogListener = new RecognizerDialogListener() {
  130. @Override
  131. public void onResults(ArrayList<RecognizerResult> arg0, boolean arg1) {
  132. // 说完话的文字存放地方
  133. for (int i = 0; i < arg0.size(); i++) {
  134. toMsg += arg0.get(i).text;
  135. }
  136. }
  137. // 获取录入内容所做的操作
  138. @Override
  139. public void onEnd(SpeechError arg0) {
  140. if (arg0 == null) {
  141. Log.i(tag, "=============================" + toMsg
  142. + "=========================");
  143. sendMessage(toMsg);
  144. }
  145. }
  146. };
  147. public void initSynthesizerplayer(String result) {
  148. SynthesizerPlayer createSynthesizerPlayer = SynthesizerPlayer
  149. .createSynthesizerPlayer(this, "appid=5212ef0a");
  150. // 参数设置发音的口音
  151. createSynthesizerPlayer.setVoiceName("xiaoyu");
  152. createSynthesizerPlayer.playText(result, "tts_buffer_time=2000",
  153. synbgListener);
  154. }
  155. SynthesizerPlayerListener synbgListener = new SynthesizerPlayerListener() {
  156. public void onPlayBegin() {
  157. // 播放开始回调,表示已获得第一块缓冲区音频开始播放
  158. }
  159. public void onBufferPercent(int percent, int beginPos, int endPos) {
  160. // 缓冲回调,通知当前缓冲进度
  161. }
  162. public void onPlayPaused() {
  163. // 暂停通知,表示缓冲数据播放完成,后续的音频数据正在获取
  164. }
  165. public void onPlayResumed() {
  166. // 暂停通知后重新获取到后续音频,表示重新开始播放
  167. }
  168. public void onPlayPercent(int percent, int beginPos, int endPos) {
  169. // 播放回调,通知当前播放进度
  170. }
  171. public void onEnd(SpeechError error) {
  172. }
  173. };
  174. private void scrollMsgToBottom() {
  175. mMsgs.post(new Runnable() {
  176. @Override
  177. public void run() {
  178. // Select the last row so it will scroll into view...
  179. mMsgs.setSelection(mAdapter.getCount() - 1);
  180. }
  181. });
  182. }
  183. }


布局文件:

  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:layout_height="match_parent"
  5. tools:context=".MainActivity" >
  6. <RelativeLayout
  7. android:id="@+id/id_ly_top"
  8. android:layout_width="fill_parent"
  9. android:layout_height="45dp"
  10. android:layout_alignParentTop="true"
  11. android:background="@drawable/title_bar" >
  12. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:layout_centerInParent="true"
  16. android:text="小慕"
  17. android:textColor="#ffffff"
  18. android:textSize="22sp" />
  19. </RelativeLayout>
  20. <RelativeLayout
  21. android:id="@+id/id_ly_bottom"
  22. android:layout_width="fill_parent"
  23. android:layout_height="55dp"
  24. android:layout_alignParentBottom="true"
  25. android:background="@drawable/bottom_bar" >
  26. <Button
  27. android:id="@+id/btn_voice"
  28. android:layout_width="40dp"
  29. android:layout_height="40dp"
  30. android:layout_centerVertical="true"
  31. android:background="@drawable/voice_button_bg" />
  32. <Button
  33. android:id="@+id/sent_msg"
  34. android:layout_width="60dp"
  35. android:layout_height="40dp"
  36. android:layout_alignParentRight="true"
  37. android:layout_centerVertical="true"
  38. android:background="@drawable/sent_button_bg"
  39. android:text="发送"
  40. android:textSize="15sp" />
  41. <EditText
  42. android:id="@+id/id_input_msg"
  43. android:layout_width="fill_parent"
  44. android:layout_height="40dp"
  45. android:layout_centerVertical="true"
  46. android:layout_marginLeft="10dp"
  47. android:layout_marginRight="10dp"
  48. android:layout_toLeftOf="@id/sent_msg"
  49. android:layout_toRightOf="@id/btn_voice"
  50. android:background="@drawable/login_edit_normal"
  51. android:hint="在此输入内容..."
  52. android:textSize="18sp" />
  53. </RelativeLayout>
  54. <ListView
  55. android:id="@+id/id_listview_msgs"
  56. android:layout_width="fill_parent"
  57. android:layout_height="fill_parent"
  58. android:layout_above="@id/id_ly_bottom"
  59. android:layout_below="@id/id_ly_top"
  60. android:divider="@null"
  61. android:dividerHeight="5dp" >
  62. </ListView>
  63. </RelativeLayout>


  1. /**
  2. * ListView的适配器
  3. */
  4. package com.example.moo;
  5. import java.text.SimpleDateFormat;
  6. import java.util.List;
  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. import com.example.bean.ChatMessage;
  14. import com.example.bean.ChatMessage.Type;
  15. public class ChatMessageAdapter extends BaseAdapter {
  16. private LayoutInflater mInflater;
  17. private List<ChatMessage> mDatas;
  18. public ChatMessageAdapter(Context context, List<ChatMessage> mDatas) {
  19. mInflater = LayoutInflater.from(context);
  20. this.mDatas = mDatas;
  21. }
  22. @Override
  23. public int getCount() {
  24. return mDatas.size();
  25. }
  26. @Override
  27. public Object getItem(int position) {
  28. return mDatas.get(position);
  29. }
  30. @Override
  31. public long getItemId(int position) {
  32. return position;
  33. }
  34. @Override
  35. public View getView(int position, View convertView, ViewGroup parent) {
  36. ChatMessage chatMessage = mDatas.get(position);
  37. ViewHolder holder = null;
  38. if (convertView == null) {
  39. //通过ItemType设置不同的布局
  40. if (getItemViewType(position) == 0) {
  41. convertView = mInflater.inflate(R.layout.item_from_msg, null);
  42. holder = new ViewHolder();
  43. holder.mDate = (TextView) convertView.findViewById(R.id.from_msg_date);
  44. holder.mMsg = (TextView) convertView.findViewById(R.id.from_msg_info);
  45. }else{
  46. convertView = mInflater.inflate(R.layout.item_to_msg, null);
  47. holder = new ViewHolder();
  48. holder.mDate = (TextView) convertView.findViewById(R.id.to_msg_date);
  49. holder.mMsg = (TextView) convertView.findViewById(R.id.to_msg_info);
  50. }
  51. convertView.setTag(holder);
  52. }else{
  53. holder = (ViewHolder) convertView.getTag();
  54. }
  55. //设置数据
  56. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  57. holder.mDate.setText(df.format(chatMessage.getDate()));
  58. holder.mMsg.setText(chatMessage.getMsg());
  59. return convertView;
  60. }
  61. private final class ViewHolder {
  62. TextView mDate;
  63. TextView mMsg;
  64. }
  65. @Override
  66. public int getItemViewType(int position) {
  67. ChatMessage chatMessage = mDatas.get(position);
  68. if (chatMessage.getType() == Type.INCOMING) {
  69. return 0;
  70. }
  71. return 1;
  72. }
  73. @Override
  74. public int getViewTypeCount() {
  75. return 2;
  76. }
  77. }


  1. package com.example.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9. import java.net.URLEncoder;
  10. import java.util.Date;
  11. import com.example.bean.ChatMessage;
  12. import com.example.bean.ChatMessage.Type;
  13. import com.example.bean.Result;
  14. import com.google.gson.Gson;
  15. import com.google.gson.JsonSyntaxException;
  16. /**
  17. * get->网络
  18. * @author TCL
  19. */
  20. public class HttpUtils {
  21. private static final String URL = "http://www.tuling123.com/openapi/api";
  22. private static final String API_KEY = "92a430f5b67795aa286554a464cbe827";
  23. public static String doGet(String msg) {
  24. String result = "";
  25. String url = setParams(msg);
  26. URL urlNet;
  27. try {
  28. urlNet = new URL(url);
  29. HttpURLConnection conn = (HttpURLConnection) urlNet
  30. .openConnection();
  31. conn.setReadTimeout(5000);
  32. conn.setConnectTimeout(5000);
  33. conn.setRequestMethod("GET");
  34. conn.connect();
  35. BufferedReader reader = new BufferedReader(new InputStreamReader(
  36. conn.getInputStream(), "utf-8"));
  37. StringBuffer sb = new StringBuffer();
  38. String line = "";
  39. while ((line = reader.readLine()) != null) {
  40. sb.append(line);
  41. }
  42. result = new String(sb);
  43. reader.close();
  44. conn.disconnect();
  45. } catch (MalformedURLException e) {
  46. e.printStackTrace();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. return result;
  51. }
  52. /**
  53. * 拼接url
  54. * @param msg
  55. * @return
  56. */
  57. public static String setParams(String msg) {
  58. String url = "";
  59. try {
  60. url = URL + "?key=" + API_KEY + "&info="
  61. + URLEncoder.encode(msg, "utf-8");
  62. } catch (UnsupportedEncodingException e) {
  63. e.printStackTrace();
  64. }
  65. return url;
  66. }
  67. /*
  68. * 发送一个消息,得到返回的消息
  69. */
  70. public static ChatMessage sendMessage(String msg){
  71. ChatMessage chatMessage = new ChatMessage();
  72. String jsonRes = doGet(msg);
  73. Gson gson = new Gson();
  74. try {
  75. Result result = gson.fromJson(jsonRes,Result.class);
  76. chatMessage.setMsg(result.getText());
  77. } catch (JsonSyntaxException e) {
  78. chatMessage.setMsg("服务器繁忙!");
  79. }
  80. chatMessage.setDate(new Date());
  81. chatMessage.setType(Type.INCOMING);
  82. return chatMessage;
  83. }
  84. }


Bean:

  1. package com.example.bean;
  2. import java.util.Date;
  3. public class ChatMessage {
  4. private String name;
  5. private String msg;
  6. private Type type;
  7. private Date date;
  8. public enum Type {
  9. INCOMING, OUTCOMING
  10. }
  11. public ChatMessage(){
  12. }
  13. public ChatMessage(String msg,Date date,Type type){
  14. this.msg = msg;
  15. this.date =date;
  16. this.type = type;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getMsg() {
  25. return msg;
  26. }
  27. public void setMsg(String msg) {
  28. this.msg = msg;
  29. }
  30. public Type getType() {
  31. return type;
  32. }
  33. public void setType(Type type) {
  34. this.type = type;
  35. }
  36. public Date getDate() {
  37. return date;
  38. }
  39. public void setDate(Date date) {
  40. this.date = date;
  41. }
  42. }

  1. package com.example.bean;
  2. public class Result {
  3. private int code;
  4. private String text;
  5. public int getCode() {
  6. return code;
  7. }
  8. public void setCode(int code) {
  9. this.code = code;
  10. }
  11. public String getText() {
  12. return text;
  13. }
  14. public void setText(String text) {
  15. this.text = text;
  16. }
  17. }


测试类:

  1. package com.example.test;
  2. import android.test.AndroidTestCase;
  3. import com.example.utils.HttpUtils;
  4. public class TestHttpUtils extends AndroidTestCase {
  5. public void TestSendInfo() {
  6. String res = HttpUtils.doGet("给我讲个笑话");
  7. System.out.println("---------------------"+res);
  8. res = HttpUtils.doGet("给我讲个鬼故事");
  9. System.out.println("---------------------"+res);
  10. res = HttpUtils.doGet("你好");
  11. System.out.println("---------------------"+res);
  12. res = HttpUtils.doGet("你是谁");
  13. System.out.println("---------------------"+res);
  14. }
  15. }



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