您的位置:首页 > 其它

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

2015-12-05 14:26 363 查看
/**
* MainActivity
*/
package com.example.moo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.bean.ChatMessage;
import com.example.bean.ChatMessage.Type;
import com.example.utils.HttpUtils;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SynthesizerPlayer;
import com.iflytek.speech.SynthesizerPlayerListener;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;

public class MainActivity extends Activity implements OnClickListener {

protected static final String tag = "MainActivity";
private ListView mMsgs;
private ChatMessageAdapter mAdapter;
private List<ChatMessage> mDatas;

private EditText mInputMsg;
private Button mSendMsg;
private Button mBtnVoice;

private boolean isVoice;

private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// 等待接收,子线程完成数据返回
ChatMessage fromMessage = (ChatMessage) msg.obj;
mDatas.add(fromMessage);
scrollMsgToBottom();// listView滚动到底部
mAdapter.notifyDataSetChanged();
if (isVoice) {
// 来自语音的话要识别并且说话
initSynthesizerplayer(fromMessage.getMsg());
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

initView();
initData();
// 初始化事件
initListener();

}

private void initView() {
mMsgs = (ListView) findViewById(R.id.id_listview_msgs);
mInputMsg = (EditText) findViewById(R.id.id_input_msg);
mSendMsg = (Button) findViewById(R.id.sent_msg);
mBtnVoice = (Button) findViewById(R.id.btn_voice);
}

private void initData() {
mDatas = new ArrayList<ChatMessage>();
mDatas.add(new ChatMessage("您好,小慕为您服务", new Date(), Type.INCOMING));
mAdapter = new ChatMessageAdapter(this, mDatas);
mMsgs.setAdapter(mAdapter);
}

private void initListener() {
mSendMsg.setOnClickListener(this);
mBtnVoice.setOnClickListener(this);
}

private String toMsg = "";

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sent_msg:
isVoice = false;
toMsg = mInputMsg.getText().toString();
sendMessage(toMsg);
break;
case R.id.btn_voice:
isVoice = true;
initRecognizerDialog();
break;
}
}

/**
* 发送消息
*
* @param toMsg
*/
private void sendMessage(final String toMsg) {
if (TextUtils.isEmpty(toMsg)) {
Toast.makeText(MainActivity.this, "消息不能为空!", Toast.LENGTH_SHORT)
.show();
return;
}
ChatMessage toMessage = new ChatMessage();
toMessage.setDate(new Date());
toMessage.setMsg(toMsg);
toMessage.setType(Type.OUTCOMING);
mDatas.add(toMessage);
mAdapter.notifyDataSetChanged();
mInputMsg.setText("");

new Thread() {
public void run() {
ChatMessage fromMeString = HttpUtils.sendMessage(toMsg);
Message m = Message.obtain();
m.obj = fromMeString;
mHandler.sendMessage(m);
};
}.start();
}

// 准备说话
private void initRecognizerDialog() {
RecognizerDialog recognizerDialog = new RecognizerDialog(this,
"appid=5212ef0a");
toMsg = "";
recognizerDialog.setEngine("sms", null, null);
recognizerDialog.setListener(dialogListener);
recognizerDialog.show();
}

RecognizerDialogListener dialogListener = new RecognizerDialogListener() {

@Override
public void onResults(ArrayList<RecognizerResult> arg0, boolean arg1) {
// 说完话的文字存放地方
for (int i = 0; i < arg0.size(); i++) {
toMsg += arg0.get(i).text;
}
}

// 获取录入内容所做的操作
@Override
public void onEnd(SpeechError arg0) {
if (arg0 == null) {
Log.i(tag, "=============================" + toMsg
+ "=========================");
sendMessage(toMsg);
}
}
};

public void initSynthesizerplayer(String result) {
SynthesizerPlayer createSynthesizerPlayer = SynthesizerPlayer
.createSynthesizerPlayer(this, "appid=5212ef0a");
// 参数设置发音的口音
createSynthesizerPlayer.setVoiceName("xiaoyu");
createSynthesizerPlayer.playText(result, "tts_buffer_time=2000",
synbgListener);
}

SynthesizerPlayerListener synbgListener = new SynthesizerPlayerListener() {
public void onPlayBegin() {
// 播放开始回调,表示已获得第一块缓冲区音频开始播放
}

public void onBufferPercent(int percent, int beginPos, int endPos) {
// 缓冲回调,通知当前缓冲进度
}

public void onPlayPaused() {
// 暂停通知,表示缓冲数据播放完成,后续的音频数据正在获取
}

public void onPlayResumed() {
// 暂停通知后重新获取到后续音频,表示重新开始播放
}

public void onPlayPercent(int percent, int beginPos, int endPos) {
// 播放回调,通知当前播放进度
}

public void onEnd(SpeechError error) {
}
};

private void scrollMsgToBottom() {
mMsgs.post(new Runnable() {
@Override
public void run() {
// Select the last row so it will scroll into view...
mMsgs.setSelection(mAdapter.getCount() - 1);
}
});
}
}


布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<RelativeLayout
android:id="@+id/id_ly_top"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:background="@drawable/title_bar" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="小慕"
android:textColor="#ffffff"
android:textSize="22sp" />
</RelativeLayout>

<RelativeLayout
android:id="@+id/id_ly_bottom"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:background="@drawable/bottom_bar" >

<Button
android:id="@+id/btn_voice"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:background="@drawable/voice_button_bg" />

<Button
android:id="@+id/sent_msg"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/sent_button_bg"
android:text="发送"
android:textSize="15sp" />

<EditText
android:id="@+id/id_input_msg"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@id/sent_msg"
android:layout_toRightOf="@id/btn_voice"
android:background="@drawable/login_edit_normal"
android:hint="在此输入内容..."
android:textSize="18sp" />
</RelativeLayout>

<ListView
android:id="@+id/id_listview_msgs"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/id_ly_bottom"
android:layout_below="@id/id_ly_top"
android:divider="@null"
android:dividerHeight="5dp" >
</ListView>

</RelativeLayout>


/**
* ListView的适配器
*/
package com.example.moo;

import java.text.SimpleDateFormat;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.bean.ChatMessage;
import com.example.bean.ChatMessage.Type;

public class ChatMessageAdapter extends BaseAdapter {

private LayoutInflater mInflater;
private List<ChatMessage> mDatas;

public ChatMessageAdapter(Context context, List<ChatMessage> mDatas) {
mInflater = LayoutInflater.from(context);
this.mDatas = mDatas;
}

@Override
public int getCount() {
return mDatas.size();
}

@Override
public Object getItem(int position) {
return mDatas.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ChatMessage chatMessage = mDatas.get(position);
ViewHolder holder = null;
if (convertView == null) {
//通过ItemType设置不同的布局
if (getItemViewType(position) == 0) {
convertView = mInflater.inflate(R.layout.item_from_msg, null);
holder = new ViewHolder();
holder.mDate = (TextView) convertView.findViewById(R.id.from_msg_date);
holder.mMsg = (TextView) convertView.findViewById(R.id.from_msg_info);
}else{
convertView = mInflater.inflate(R.layout.item_to_msg, null);
holder = new ViewHolder();
holder.mDate = (TextView) convertView.findViewById(R.id.to_msg_date);
holder.mMsg = (TextView) convertView.findViewById(R.id.to_msg_info);
}
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}

//设置数据
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
holder.mDate.setText(df.format(chatMessage.getDate()));
holder.mMsg.setText(chatMessage.getMsg());

return convertView;
}

private final class ViewHolder {
TextView mDate;
TextView mMsg;
}

@Override
public int getItemViewType(int position) {
ChatMessage chatMessage = mDatas.get(position);
if (chatMessage.getType() == Type.INCOMING) {
return 0;
}
return 1;
}

@Override
public int getViewTypeCount() {
return 2;
}
}


package com.example.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import com.example.bean.ChatMessage;
import com.example.bean.ChatMessage.Type;
import com.example.bean.Result;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
* get->网络
* @author TCL
*/
public class HttpUtils {

private static final String URL = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "92a430f5b67795aa286554a464cbe827";

public static String doGet(String msg) {
String result = "";
String url = setParams(msg);

URL urlNet;
try {
urlNet = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlNet
.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.connect();

BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = new String(sb);
reader.close();
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

/**
* 拼接url
* @param msg
* @return
*/
public static String setParams(String msg) {
String url = "";
try {
url = URL + "?key=" + API_KEY + "&info="
+ URLEncoder.encode(msg, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}

/*
* 发送一个消息,得到返回的消息
*/
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();

String jsonRes = doGet(msg);
Gson gson = new Gson();
try {
Result result = gson.fromJson(jsonRes,Result.class);
chatMessage.setMsg(result.getText());
} catch (JsonSyntaxException e) {
chatMessage.setMsg("服务器繁忙!");
}
chatMessage.setDate(new Date());
chatMessage.setType(Type.INCOMING);
return chatMessage;
}
}


Bean:

package com.example.bean;

import java.util.Date;

public class ChatMessage {

private String name;
private String msg;
private Type type;
private Date date;

public enum Type {
INCOMING, OUTCOMING
}

public ChatMessage(){

}
public ChatMessage(String msg,Date date,Type type){
this.msg = msg;
this.date =date;
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public Type getType() {
return type;
}

public void setType(Type type) {
this.type = type;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

}

package com.example.bean;

public class Result {

private int code;
private String text;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}

}


测试类:

package com.example.test;

import android.test.AndroidTestCase;

import com.example.utils.HttpUtils;

public class TestHttpUtils extends AndroidTestCase {

public void TestSendInfo() {

String res = HttpUtils.doGet("给我讲个笑话");
System.out.println("---------------------"+res);
res = HttpUtils.doGet("给我讲个鬼故事");
System.out.println("---------------------"+res);
res = HttpUtils.doGet("你好");
System.out.println("---------------------"+res);
res = HttpUtils.doGet("你是谁");
System.out.println("---------------------"+res);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: