心血来潮后的一个语音软件

直接上视频

http://v.youku.com/v_show/id_XNDA4ODU5NzMy.html

Android源码

package com.eyet.demo.voice;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class RecognizerIntent_TestActivity extends Activity {
	private static final int TIMEOUT = 3000; // Resend timeout (milliseconds)
	private static final int MAXTRIES = 5; // Maximum retransmissions
	private static final String REPLY = "OK";
	private static final String SERVERIP = "192.168.0.133";
	private static final int SERVERPORT = 3693;

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;

	private String cmd;
	private ImageView image_but;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		image_but = (ImageView) this.findViewById(R.id.image_but);

		image_but.setOnClickListener(new myRecognizerIntentListener());

	}

	public void ProtocolHandler() {
		if (cmd != null && cmd.length() != 0) {
			try {
				DatagramSocket socket = new DatagramSocket();
				socket.setSoTimeout(TIMEOUT);
				byte[] bytesToSend = cmd.getBytes();

				DatagramPacket sendPacket = new DatagramPacket(bytesToSend,
						bytesToSend.length, InetAddress.getByName(SERVERIP),
						SERVERPORT);
				int len = REPLY.getBytes().length;
				DatagramPacket receivePacket = new DatagramPacket(
						new byte[len], len);
				int tries = 0; // Packets may be lost, so we have to keep trying
				boolean receivedResponse = false;
				do {
					socket.send(sendPacket); // Send the echo string
					try {
						socket.receive(receivePacket);

						if (!receivePacket.getAddress().equals(
								InetAddress.getByName(SERVERIP))) {// Check
																	// source
							throw new IOException(
									"Received packet from an unknown source");
						}
						receivedResponse = true;
					} catch (InterruptedIOException e) { // We did not get
															// anything
						tries += 1;
						Log.e("Recevice Error", e.getMessage());
					}
				} while ((!receivedResponse) && (tries < MAXTRIES));

				if (receivedResponse) {
					Toast.makeText(RecognizerIntent_TestActivity.this,
							new String(receivePacket.getData()),
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(RecognizerIntent_TestActivity.this,
							"No response -- giving up.", Toast.LENGTH_LONG)
							.show();
				}

			} catch (IOException e) {
				Log.e("Socket Error", e.getMessage());
			}
		}
	}



	public class myRecognizerIntentListener implements OnClickListener {
		public void onClick(View v) {

			try {
				Intent intent = new Intent(
						RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // 语言模式和自由形式的语音识别
				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
						RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // 提示语言开始
				intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请开始语音"); //
				
				startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
				
				
			} catch (ActivityNotFoundException e) {
				Toast.makeText(RecognizerIntent_TestActivity.this, "找不到语音设备",
						Toast.LENGTH_LONG).show();
			}

			
		}
	}
	
	/**
	 * @param voice 语音字符串
	 * @return  协议命令 | null 没有匹配
	 */
	public String getCmd(String voice){
		
		if(voice == null)
			return null;
		
		String open = "打开";
		String close = "关闭";
		String result = null;
		
		if(voice.indexOf(open) != -1){
			
			if(voice.indexOf("浏览器") != -1){
				result = "open_firefox";
			}else if(voice.indexOf("百度") != -1){
				result = "open_baidu";
			}else if(voice.indexOf("记事本") != -1){
				result = "open_notepad";
			}else if(voice.toLowerCase().indexOf("qq") != -1){
				result = "open_qq";
			}else if(voice.toLowerCase().indexOf("wps") != -1){
				result = "open_wps";
			}else if(voice.toLowerCase().indexOf("e") != -1){
				result = "open_e";
			}
			
			
		}else if(voice.indexOf(close) != -1){
			if(voice.indexOf("浏览器") != -1){
				result = "close_firefox";
			}else if(voice.indexOf("记事本") != -1){
				result = "close_notepad";
			}else if(voice.toLowerCase().indexOf("wps") != -1){
				result = "close_wps";
			}else if(voice.indexOf("电脑") != -1){
				result = "close_computer";
			}
			
		}
		
		return result;
	}

	// 语音结束时的回调函数
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			// 取得语音的字符
			ArrayList<String> results = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

			String str = "";
			for (int i = 0; i < results.size(); i++) {
				str += results.get(i);
				cmd = getCmd(results.get(i));
				if(cmd != null){
					break;
				}
			}
			//Toast.makeText(this, cmd+"::==::" + str, Toast.LENGTH_LONG).show();
			
			if(cmd != null){
				ProtocolHandler();
			}
			
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
 

服务器端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;
import java.util.Map;


public class RunCmd {

	private static final int BUFMAX = 255; // Maximum size of echo datagram
	private static Map<String , Runnable> cmdThreadPool;
	
	public static void main(String[] args) {
		
		
		RunCmd rc = new RunCmd();
		rc.serverRun();

	}
	
	
	public RunCmd() {
		cmdThreadPool = new HashMap<String , Runnable>();
		cmdThreadPool.put("open_firefox", new cmdRunnable("C:\\Program Files\\Mozilla Firefox\\firefox.exe"));
		cmdThreadPool.put("open_baidu", new cmdRunnable("C:\\Program Files\\Mozilla Firefox\\firefox.exe http://www.baidu.com"));
		cmdThreadPool.put("close_firefox", new cmdRunnable("taskkill /im firefox.exe"));
		cmdThreadPool.put("open_notepad", new cmdRunnable("notepad"));
		cmdThreadPool.put("close_notepad", new cmdRunnable("taskkill /im notepad.exe"));
		cmdThreadPool.put("open_qq", new cmdRunnable("C:\\Program Files\\Tencent\\QQ\\Bin\\QQProtect\\Bin\\QQProtect.exe"));
		cmdThreadPool.put("open_wps", new cmdRunnable("C:\\Program Files\\Kingsoft\\WPS Office Personal\\office6\\wps.exe /w"));
		cmdThreadPool.put("close_wps", new cmdRunnable("taskkill /im wps.exe"));
		cmdThreadPool.put("open_e", new cmdRunnable("explorer e:"));
		cmdThreadPool.put("close_computer", new cmdRunnable("shutdown /s /t 0"));
	}


	public void serverRun(){
		try {
			DatagramSocket socket = new DatagramSocket(3693);
			DatagramPacket packet = new DatagramPacket(new byte[BUFMAX], BUFMAX);
			
			
		    while (true) { // Run forever, receiving and echoing datagrams
		    	socket.receive(packet); // Receive packet from client
		    	
		    	String cmd = new String(packet.getData(),packet.getOffset() , packet.getLength());
		    	
		    	System.out.println(cmd);
		    	
		    	byte[] replayMsg;
		    	if(handlerCmd(cmd)){
		    		replayMsg = new String("OK").getBytes();
		    		
		    	}else{
		    		replayMsg = new String("NO").getBytes();
		    		
		    	}
		    	DatagramPacket replayPacket = new DatagramPacket(replayMsg,replayMsg.length,
		    			packet.getAddress() , packet.getPort());
		        socket.send(replayPacket); // Send the same packet back to client
		    	
		        packet.setLength(BUFMAX); // Reset length to avoid shrinking buffer
		    }
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	    
	    
	}
	
	
	public boolean handlerCmd(String cmd){
		Runnable cmdRun = cmdThreadPool.get(cmd.trim());
		
		if(cmdRun != null){
			new Thread(cmdRun).start();
			return true;
		}else{
			return false;
		}
		
	}
	
	public class cmdRunnable implements Runnable{
		private String cmd;
		public cmdRunnable(String cmd){
			this.cmd = cmd;
		}
		
		public void run(){
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	
	/*
	
	public class OpenFireFox implements Runnable{
		public void run(){
			String open_cmd = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class OpenBaiDu implements Runnable{
		public void run(){
			String open_cmd = "C:\\Program Files\\Mozilla Firefox\\firefox.exe http://www.baidu.com";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class CloseFireFox implements Runnable{
		public void run(){
			String close_cmd= "taskkill /im firefox.exe";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(close_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public class OpenNotepad implements Runnable{
		public void run(){
			String open_cmd = "notepad";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class CloseNotepad implements Runnable{
		public void run(){
			String close_cmd= "taskkill /im notepad.exe";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(close_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class OpenQQ implements Runnable{
		public void run(){
			String open_cmd = "C:\\Program Files\\Tencent\\QQ\\Bin\\QQProtect\\Bin\\QQProtect.exe";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class OpenWPS implements Runnable{
		public void run(){
			String open_cmd = "C:\\Program Files\\Kingsoft\\WPS Office Personal\\office6\\wps.exe /w";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class CloseWPS implements Runnable{
		public void run(){
			String close_cmd= "taskkill /im wps.exe";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(close_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class OpenE implements Runnable{
		public void run(){
			String open_cmd = "explorer e:";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class CloseComputer implements Runnable{
		public void run(){
			String open_cmd = "shutdown /s /t 0";
			try {
				Runtime run = Runtime.getRuntime();
				run.exec(open_cmd);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}*/

}
 

相关推荐