现在的位置: 首页 > 综合 > 正文

豆豆秘书1.0v(android)

2013年10月10日 ⁄ 综合 ⁄ 共 8271字 ⁄ 字号 评论关闭
学习android开发有一段时间了,一直也没有做出什么有意思的软件,学校放假闲来无事,写些软件,用以对之前学过的知识的巩固。

这个软件的名字是女朋友起的,就凑合着用吧  哈哈....

下面进入正题了

软件总体构架如图

1.语音输入识别

public class SpeechRecognition   {
	private Intent intent = null;
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 4321;
	Activity activity;
	public SpeechRecognition(Context context){
		activity = (Activity)context;
	}
	public void start(){
		intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");
		activity.startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
	}
}

2.模拟Http请求

public class HttpTools {

    
    static int TIMEOUT = 5000;//默认超时时间
    static String CHARSET = "iso-8859-1";//默认字符编码
    static String TYPE = "text/html";//默认接收的html类型 
    static String SRCLANGUAGE = "zh-CN";//默认的语言源
    static String TARGETLANGUAGE = "en";//默认翻译的目标语言targetLanguage;
    static String TTSLANGUAGE = "en";//默认的发音语言

	public static InputStream getInputStreamFromUrl(String urlString)
			throws IOException {
		return HttpTools.getInputStreamFromUrl(urlString, CHARSET);
	}

	public static InputStream getInputStreamFromUrl(String urlString,
			String charset) throws IOException {
		return HttpTools.getInputStreamFromUrl(urlString, charset, TIMEOUT);
	}

	public static InputStream getInputStreamFromUrl(String urlString,
			String charset, int timeout) throws IOException {
		return HttpTools.getInputStreamFromUrl(urlString, charset, TYPE,
				timeout);
	}
	
	
    /*
     * 函数功能:从传入的URL中得到一个InputStream流对象
     * 输入参数: urlString URL地址
     *          charset  编码类型
     *          type     接收的类型
     *          timeout  http请求超时时间
     * 返回值类型:InputStream
     * 创建人:twt
     * 2012.7.21
     */
	public static InputStream getInputStreamFromUrl(String urlString,
			String charset, String type, int timeout) throws IOException {
		if (urlString == null || urlString.length() == 0) {
			return null;
		}
		// 判断url地址是https 还是http
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString)
				.intern();
		// 构造一个URL对象
		URL url = new URL(urlString);
		// 打开一个到URL对象的连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setRequestProperty(
				"User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// 增加报头,模拟浏览器,防止屏蔽
		conn.setRequestProperty("Accept", type);// 只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些
		// 设置超时时间
		conn.setConnectTimeout(timeout);
		try {
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
		} catch (IOException e) {
			return null;
		}
		// 从HttpURLConnection对象中得到输入流
		InputStream input = conn.getInputStream();
		return input;
	}
    
	
    /*
     * 函数功能:以String的形式从inputStream流中取回数据
     * 输入参数: InputStream
     * 返回值类型:String
     * 创建人:twt
     * 2012.7.21
     */
	public static String getStringsFromInputStream(InputStream is,
			String charset) throws UnsupportedEncodingException, IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				charset));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\r\n");
		}
		if (reader != null) {
			reader.close();
		}
		return sb.toString();
	}

	public static String getStringsFromInputStream(InputStream is)
			throws UnsupportedEncodingException, IOException {
		return HttpTools.getStringsFromInputStream(is, CHARSET);
	}
    
	
    /*
     * 函数功能:以byte[]的形式从inputStream流中取回数据
     * 输入参数: InputStream
     * 返回值类型:byte[]
     * 创建人:twt
     * 2012.7.21
     */
	public static byte[] getBytesFromInputStream(InputStream is)
			throws IOException {
		 
		byte[] buf = new byte[1024 * 4];// 缓冲区
		byte[] temp = new byte[1024 * 128];// 用来临时保存从缓冲区中得到的数据
		int readLength = 0;// 从缓冲区读到的数据的实际长度
		int totalLength = 0;// 从缓冲区取得的数据总长度
		while (((readLength = is.read(buf)) != -1)) {
			// 累加从缓冲区取得的数据长度
			// 将从缓冲区得到的数据临时保存在temp数组中
			System.arraycopy(buf, 0, temp, totalLength,  readLength);
			totalLength += readLength;
		}
		// 根据从缓冲区取得的数据总长度构造一个数组
		byte[] bytes = new byte[totalLength];
		// 将从temp数组中的数据复制到bytes中
		System.arraycopy(temp, 0, bytes, 0, totalLength);
		return bytes;
	}
}

3.翻译

public class Translate {
	
	static int TIMEOUT = 5000;// 默认超时时间
	static String CHARSET = "iso-8859-1";// 默认字符编码
	static String TYPE = "text/html";// 默认接收的html类型
	static String SRCLANGUAGE = "zh-CN";// 默认的语言源
	static String TARGETLANGUAGE = "en";// 默认翻译的目标语言targetLanguage;
	static String TTSLANGUAGE = "en";// 默认的发音语言
	
	
	 /*
     * 从http请求得到的结果中提取翻译后的结果
     * 输入参数:s Http请求结果字符串
     * 返回值:String 类型  翻译后的字符串
     * 创建人:twt
     * 2012.7.21
     * 例:"how are you"的google翻译
     * 传入参数: [[["你怎么样","how are you","Nǐ zěnme yàng",""]],[["词组",["你好"],[["你好",["How are you"]]]]],"en",,[["你怎么样",[5],0,0,1000,0,3,0]],[["how are~~V you",4,,,""],["how are you",5,[["你怎么样",1000,0,0],["你好吗",0,0,0],["你怎么",0,0,0]],[[0,11]],"how are you"]],,,[["en"]],3]
                   返回的结果:你怎么样
     */
	public static String getTranslateResult(String s) {
		return s.substring(4, s.indexOf('"', 4));
	}

    /*
     * 功能:从Http请求返回的结果中得到回复信息
     * 输入参数:msg Http请求结果字符串
     * 返回值:Robot的回复
     * 创建人:twt
     * 2012.7.22
     * 例:
        msg:  {"response":"那你好嗎","id":19591829,"result":100,"msg":"OK."}
                     返回结果:那你好嗎
     */
    public static String getSimsimiRobotReplyMsg(String msg) {
        String replyMsg = null;
        System.out.println(msg);
        if (msg.startsWith("{\"response\":")) {
            replyMsg = msg.substring(13, msg.indexOf('"', 13));
        }
        return replyMsg;
    }

    public static String translate(String text) throws IOException {
        return translate(text, SRCLANGUAGE, TARGETLANGUAGE);
    }

    public static String translate(String text, String targetLanguage) throws IOException {
        return translate(text, SRCLANGUAGE, targetLanguage);
    }
     /*
     * 功能:将输入的文本翻译成指定的语言
     * 输入参数:
          text :要翻译的文本
          srcLanguage:源语言类型
          targetLanguage:目标语言类型
     * 返回值:翻译后的结果
     * 创建人:twt
     * 2012.7.22
     * 例:
         text: 你好吗?
         srcLanguage:zh-CN(中文)
         targetLanguage :en (英语)
                       返回结果:How are you?
     */
    public static String translate(String text, String srcLanguage, String targetLanguage) throws IOException {
        String url = null;
        url = getTranslateUrl(text, srcLanguage, targetLanguage);
        InputStream in = HttpTools.getInputStreamFromUrl(url);
        String translateResult = getTranslateResult(HttpTools.getStringsFromInputStream(in, "UTF-8"));
        return translateResult;
    }

    public static String getTranslateUrl(String text) throws UnsupportedEncodingException {
        return getTranslateUrl(text, SRCLANGUAGE, TARGETLANGUAGE);
    }
    
    /*
     * 功能:根据传入的参数构造一个google翻译的URL地址
     * 输入参数:
          text :要翻译的文本
          srcLanguage:源语言类型
          targetLanguage:目标语言类型
     * 返回值:经过编码后的URL地址
     * 创建人:twt
     * 2012.7.22
     */
    public static String getTranslateUrl(String text, String srcLanguage, String targetLanguage) throws UnsupportedEncodingException {
        text = URLEncoder.encode(text, "UTF-8");
        String url = "http://translate.google.cn/translate_a/t?client=t&text=" 
                + text + "&hl=zh-CN&sl="
                + srcLanguage + 
                "&tl=" 
                + targetLanguage + 
                "&ie=UTF-8&oe=UTF-8&multires=1&ssel=0&tsel=0&sc=1";
        return url;
    }
}

4.语音输出

public class Tts {

	private static String TTSLANGUAGE = "en";// 默认的发音语言
	@SuppressLint("SdCardPath")
	private static MediaPlayer mediaPlayer = null;
	private static File tempFile = null;
	//"http://translate.google.com.tw/translate_tts?ie=UTF-8&q=you&tl=en&prev=input";
	public static String getTtsUrl(String text, String language) throws UnsupportedEncodingException {
		text = URLEncoder.encode(text, "UTF-8");
		String ttsUrl =	"http://translate.google.com.tw/translate_tts?ie=UTF-8&q="+text+"&tl="+language+"&prev=input";
        return ttsUrl;
    }

    public static String getTtsUrl(String text) throws UnsupportedEncodingException {
        return getTtsUrl(text,TTSLANGUAGE);
    }
    public static void tts(String text) throws IOException {
    	tts(text,TTSLANGUAGE);
    }

    public static void tts(String text, String language) throws IOException {
    	String ttsUrl = getTtsUrl(text, language);
    	byte[] temp = HttpTools.getBytesFromInputStream(HttpTools.getInputStreamFromUrl(ttsUrl));
    	saveTemp(temp);
    	String path = tempFile.getPath();
    	play(path);
    }
    public static void play(String path) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException{
    	mediaPlayer = new MediaPlayer();
    	mediaPlayer.setDataSource(path);
    	mediaPlayer.prepare();
    	mediaPlayer.start();
    }
    public static boolean saveTemp(byte[] temp) throws IOException{
    	tempFile = File.createTempFile("tts", ".mp3");
    	OutputStream fos = new FileOutputStream(tempFile);
    	fos.write(temp);
    	fos.flush();
    	fos.close();
    	return true;
    }

}

5.机器人聊天

public class Robot {

	public static String sendMsgToSimsimiRobot(String msg) throws IOException {
		String url = getSimsimiUrl(msg);
		System.out.println(url);
		InputStream is = HttpTools.getInputStreamFromUrl(url);
		String reply = HttpTools.getStringsFromInputStream(is, "UTF-8");
		return getSimsimiRobotReplyMsg(reply);
	}

	public static String getSimsimiUrl(String msg)
			throws UnsupportedEncodingException {
		msg = URLEncoder.encode(msg, "UTF-8");
		msg = msg.replace("%", "%25");
		System.out.println(msg);
		return "http://www.simsimi.com/func/req?msg=" + msg + "&lc=ch";
	}

	 /*
     * 功能:从Http请求返回的结果中得到回复信息
     * 输入参数:msg Http请求结果字符串
     * 返回值:Robot的回复
     * 创建人:twt
     * 2012.7.22
     * 例:
        msg:  {"response":"那你好嗎","id":19591829,"result":100,"msg":"OK."}
                    返回结果:那你好嗎
     */
	public static String getSimsimiRobotReplyMsg(String msg) {
		String replyMsg = null;
		System.out.println(msg);
		if (msg.startsWith("{\"response\":")) {
			replyMsg = msg.substring(13, msg.indexOf('"', 13));
		}
		return replyMsg;
	}
	public static String fun(String msg){
		msg.replaceAll("%", "%25");
		return msg;
		
	}
}

 

抱歉!评论已关闭.