首页 > 代码库 > 聊天机器人(基于android)

聊天机器人(基于android)

1.本人最近写了一个小项目关于语音聊天的,采用讯飞语音引擎和数据,看看效果

技术分享

技术分享

技术分享

 

2.项目名称叫小秘书,它可以和你进行交互,可以通过语音聊天,蛮有意思的,聊天内容你也可以定制

3.如果想做这款应用,先看看我前面写的语音识别

http://www.cnblogs.com/huipengbo/p/7043384.html

4.先看清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chat"
    android:versionCode="1"
    android:versionName="1.0" >
       <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/login_user_selected"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

5.在看布局

主界面布局

<LinearLayout 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"
    android:orientation="vertical" >
    
    <ListView 
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:background="@drawable/detail_btn_bg_normal">
        <Button android:layout_width="wrap_content"
            android:onClick="click"
            android:layout_height="wrap_content"
            android:background="@drawable/bt_selector"
            android:text="开始和小秘对话"
            android:padding="5dp"
            />
    </LinearLayout>


</LinearLayout>

item布局展示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >

    <LinearLayout
        android:id="@+id/ll_up"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="2dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/category_mama01"
            android:gravity="center_vertical"
            android:padding="4dp"
            android:text="貂蝉"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="哈鲁kljflgjdljgdlf"
            android:textColor="#008"
            android:textSize="18sp" />
                <ImageView 
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:src="@drawable/logo"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/ll_down"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp">

        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:drawableRight="@drawable/app_icon"
            android:gravity="center_vertical"
            android:padding="4dp"
            android:textColor="#000"
            android:text="我"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/tv2"
            android:textColor="#080"
            android:textSize="18sp" />

    </RelativeLayout>

</LinearLayout>

6.资源配置和资产配置,资产配置参考语音识别那节随笔

技术分享

技术分享

 

 7.上源代码,有三个文件

@1MainActivity文件

package com.example.chat;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.example.chat.VoiceBean.WS;
import com.google.gson.Gson;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Telephony.Sms.Conversations;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
    
    StringBuffer strbuf;
    ListView mlv;
    private List<TalkBean> lists;
    MyAdapter adapter;
    
    private String[] answers = new String[]{"约吗?","想我吗?","我漂亮吗","喜欢我吗?","有没有做饭的想法啊","来不来?","你女朋友有我漂亮吗?","想吃我做的菜吗?",
            "看见我有没有年轻的冲动","来嘛,人家要玩游戏啊","帅哥,我受不了你神经的样子","看我的身材好不","我胸丰满不","哥哥,你快点把水拿过来","晚上请我看电影,好吗?","最近有没有回家吗?"};

    private int []imges = new int[]{R.drawable.m1,R.drawable.m2,R.drawable.m3,R.drawable.m4,R.drawable.m5,
                            R.drawable.m6,R.drawable.m7,R.drawable.m8,R.drawable.m9,R.drawable.m10,
                            R.drawable.m11,R.drawable.m12,R.drawable.m13,R.drawable.m14,R.drawable.m15,R.drawable.after19};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化语音配置对象,必须,这样才能使用MSC语音服务
        SpeechUtility.createUtility(this, SpeechConstant.APPID+"=59454d78");
        mlv = (ListView) findViewById(R.id.lv);
        lists = new ArrayList<TalkBean>();
        
        adapter = new MyAdapter();
        
        mlv.setAdapter(adapter);
        
        
    }
    
       public void click(View view){
            //创建语音识别对话框
            RecognizerDialog rd = new RecognizerDialog(this,null);
            //设置参数accent,language等参数
            rd.setParameter(SpeechConstant.LANGUAGE,"zh_cn");//中文
            rd.setParameter(SpeechConstant.ACCENT,"mandarin");//普通话
            strbuf = new StringBuffer();
            //设置回调接口
            rd.setListener(new RecognizerDialogListener() {
                
                @Override
                public void onResult(RecognizerResult arg0, boolean arg1) {
                    // TODO Auto-generated method stub
                    String  result = arg0.getResultString();
                    String data = parseJsonData(result);
                    Log.e("data",data);
                  
                    strbuf.append(data);
                    if(arg1){//回话结束
                        String voice = strbuf.toString();
                        Log.e("result",voice);
                        //初始化提问对象
                        TalkBean tb = new TalkBean(voice, -1, true);
                        lists.add(tb);
                        String ans = "没听清楚,哥哥";
                        int imgid = -1;
                        if(voice.contains("你好")){
                            ans = "你好啊";
                        }else if(voice.contains("你是")){
                            ans = "我是穿越来的貂蝉";
                        }else if(voice.contains("美女")|| voice.contains("我想你")){
                            //随机回答
                            ans = answers [(int) (Math.random()*answers.length)];
                            imgid = imges[(int) (Math.random()*imges.length)];
                        }else if(voice.contains("照片")){
                            ans ="这个就是我本人,漂亮吧";
                            imgid = imges[(int) (Math.random()*imges.length)];
                        }else if(voice.contains("天王盖地虎")){
                            ans = "宝塔镇河妖";
                            imgid =R.drawable.logo;
                        }else if(voice.contains("漂亮")){
                            ans = "谢谢哥哥夸奖";
                        }else if(voice.contains("干")){
                            ans = "来吧,干杯吧";
                            imgid = imges[(int) (Math.random()*imges.length)];
                        }
                        TalkBean tbans = new TalkBean(ans, imgid, false);
                        lists.add(tbans);
                        
                        
                        
                        //数据改变刷新适配器listview
                        adapter.notifyDataSetChanged();
                        
                        //让listview始终显示最后一个
                        mlv.setSelection(lists.size()-1);
                        //将要说的话读出来
                        read(ans);
                    }
                    
                    
                }
                
                @Override
                public void one rror(SpeechError arg0) {
                    // TODO Auto-generated method stub
                    
                }
            });
            //显示对话框
            rd.show();
        }
        /**
         * 解析json串
         * @param result
         */
        protected String parseJsonData(String json) {
        // 使用Gson来解析Json串
            Gson gson = new Gson();
            VoiceBean bean = gson.fromJson(json, VoiceBean.class);
            ArrayList<WS> ws = bean.ws;
            StringBuffer sb = new StringBuffer();
            for (WS ws2 : ws) {
                String info = ws2.cw.get(0).w;
                sb.append(info);
            }
            return sb.toString();
    }

        /**
         * 语音合成
         * @param view
         */
        public void read(String text){
            //创建合成器对象
            SpeechSynthesizer ss = SpeechSynthesizer.createSynthesizer(this, null);
            //设置参数
            ss.setParameter(SpeechConstant.VOICE_NAME, "xiaoqi");//设置发音人
            ss.setParameter(SpeechConstant.SPEED, "30");//语速设置
            ss.setParameter(SpeechConstant.VOLUME, "80");//设置音量
            ss.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);//设置为云端类型
            //ss.setParameter(SpeechConstant.TTS_AUDIO_PATH, "/mnt/sdcard/if.pcm");//设置音频保存路径,不用则注释
      
            //开始合成语音
            ss.startSpeaking(text, null);
            
        }
        
        class MyAdapter extends BaseAdapter{

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return lists.size();
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return lists.get(position);
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder vh = null;
                if(convertView == null){
                    convertView = View.inflate(getApplicationContext(), R.layout.list_item, null);
                    vh = new ViewHolder();
                    vh.ll_answer = (LinearLayout)convertView.findViewById(R.id.ll_up);
                    vh.tvanswer =  (TextView)convertView.findViewById(R.id.tv1);
                    vh.ivanswer = (ImageView) convertView.findViewById(R.id.iv);
                    
                    vh.rl_ask = (RelativeLayout)convertView. findViewById(R.id.ll_down);
                    vh.tvask = (TextView) convertView.findViewById(R.id.tv3);
                    
                    
                    convertView.setTag(vh);
                }else{
                    vh = (ViewHolder) convertView.getTag();
                }
                TalkBean tb = (TalkBean) getItem(position);
                
                if(tb.isAsk){//如果是问,则不显示回答的一方
                    vh.ll_answer.setVisibility(View.GONE);
                    vh.rl_ask.setVisibility(View.VISIBLE);
                    vh.tvask.setText(tb.text);
                }else{//如果是回答,则不显示问的一方
                    vh.ll_answer.setVisibility(View.VISIBLE);
                    vh.rl_ask.setVisibility(View.GONE);
                    vh.tvanswer.setText(tb.text);
                    //图片
                    if(tb.imageId>0){
                        vh.ivanswer.setVisibility(View.VISIBLE);
                        vh.ivanswer.setImageResource(tb.imageId);
                    }else{
                        vh.ivanswer.setVisibility(View.GONE);
                    }
                }
                
                return convertView;
            }

    
            
        }
        
        static class ViewHolder{
            public LinearLayout ll_answer;
            public TextView tvanswer;
            public ImageView ivanswer;
            
            public RelativeLayout rl_ask;
            public TextView tvask;
        
        }
}

@2问答数据封装类

package com.example.chat;
/*
 * 提问与回答的bean
 */
public class TalkBean {
    
    public String text;
    public int imageId;
    public boolean isAsk;
    
    public TalkBean(String text, int imageId, boolean isAsk) {
        super();
        this.text = text;
        this.imageId = imageId;
        this.isAsk = isAsk;
    }

}

@3返回的json数据封装类

package com.example.chat;

import java.util.ArrayList;

public class VoiceBean {
    
    public ArrayList<WS> ws;
    
    
    public class WS{
        public ArrayList<CW> cw;
        
    }
    
    public class CW{
        public String w;//说话的文字信息
    }

}

8.引用的库如下

技术分享

 

聊天机器人(基于android)