读书人

手机联接计算机server

发布时间: 2012-08-21 13:00:21 作者: rapoo

手机连接计算机server

package br.ufs.reconhecimento;?
?
import java.io.DataInputStream;?
import java.io.DataOutputStream;?
import java.io.File;?
import java.io.FileInputStream;?
import java.io.IOException;?
import java.net.Socket;?
?
import android.app.Activity;?
import android.app.AlertDialog;?
import android.content.DialogInterface;?
import android.content.Intent;?
import android.os.Bundle;?
import android.util.Log;?
import android.view.View;?
import android.view.View.OnClickListener;?
import android.widget.EditText;?
import android.widget.ImageButton;?
?
/**?
?*??
?*/?
public class Reconhecimento extends Activity implements OnClickListener {?
?
? ? static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;?
? ? static final String LOG_VOZ = "UFS-Reconhecimento";?
? ? final int INICIAR_GRAVACAO = 01;?
? ? int porta = 5158; // Porta definida no servidor?
? ? int tempoEspera = 1000;?
? ? String ipConexao = "172.20.0.189";?
? ? EditText ipEdit;?
?
? ? /**?
? ? ?* Called with the activity is first created.?
? ? ?*/?
? ? @Override?
? ? public void onCreate(Bundle savedInstanceState) {?
? ? ? ? super.onCreate(savedInstanceState);?
? ? ? ? // Inflate our UI from its XML layout description.?
? ? ? ? setContentView(R.layout.main);?
?
? ? ? ? // Get display items for later interaction?
? ? ? ? ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak);?
? ? ? ? speakButton.setPadding(10, 10, 10, 10);?
?
? ? ? ? speakButton.setOnClickListener(this);?
?
? ? ? ? //Alerta para o endere?o IP?
? ? ? ? AlertDialog.Builder alerta = new AlertDialog.Builder(this);?
? ? ? ? alerta.setTitle("IP");//+mainWifi.getWifiState());?
?
? ? ? ? ipEdit = ?new EditText(this);?
? ? ? ? ipEdit.setText(ipConexao);?
? ? ? ? alerta.setView(ipEdit);?
? ? ? ? alerta.setMessage("Por favor, Confirme o endere?o IP.");?
? ? ? ? alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() {?
? ? ? ? ? ? ? ?public void onClick(DialogInterface dialog, int which) {?
? ? ? ? ? ? ? ? ? ? ipConexao = ipEdit.getText().toString();?
? ? ? ? ? ? ? ? ? ? Log.d(LOG_VOZ, "Nova Atribui??o do Endre?o IP: " + ipConexao); } });?
? ? ? ? alerta.create();?
? ? ? ? alerta.show();?
?
? ? }?
?
?
? ? /**?
? ? ?* Handle the click on the start recognition button.?
? ? ?*/?
? ? public void onClick(View v) {?
? ? ? ? if (v.getId() == R.id.btn_speak) {?
? ? ? ? ? ? //startVoiceRecognitionActivity();?
? ? ? ? ? Log.d(LOG_VOZ, "Iniciando a próxima tela");?
? ? ? ? ? Intent recordIntent = new Intent(this, GravacaoAtivity.class);?
? ? ? ? ? Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)");?
? ? ? ? ? startActivityForResult(recordIntent, INICIAR_GRAVACAO);?
? ? ? ? ? Log.d(LOG_VOZ, "Grava??o iniciada ...");?
? ? ? ? }?
? ? }?
?
?
? ? /**?
? ? ?* Handle the results from the recognition activity.?
? ? ?*/?
? ? @Override?
? ? protected void onActivityResult(int requestCode, int resultCode, Intent data) {?
? ? ?Log.d(LOG_VOZ, "Iniciando onActivityResult()");?
? ? ?if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) {?
? ? ? ? ? String path = data.getStringExtra(GravacaoAtivity.RETORNO);?
? ? ? ? ? conexaoSocket(path);?
? ? ?}?
? ? ?else?
? ? ? ? ? Log.e(LOG_VOZ, "Resultado Inexperado ...");?
? ? }?
?
? ? private void conexaoSocket(String path) {?
? ? ?Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera);?
? ? ?if(socket == null)?
? ? ? ? ? return;?
? ? ?try {?
? ? ? ? ? ? ? ?DataOutputStream conexao = new DataOutputStream(socket.getOutputStream());?
? ? ? ? ? ? ? ?Log.d(LOG_VOZ, "Acessando arquivo ...");?
? ? ? ? ? ? ? ?File file = new File(path);?
? ? ? ? ? ? ? ?DataInputStream arquivo = new DataInputStream(new FileInputStream(file));?
? ? ? ? ? ? ? ?Log.d(LOG_VOZ, "Iniciando Transmiss?o ...");?
? ? ? ? ? ? ? ?conexao.writeLong(file.length());?
? ? ? ? ? ? ? ?for(int i = 0; i < file.length(); i++)?
? ? ? ? ? ? ? ? ? ? conexao.writeByte(arquivo.readByte());?
? ? ? ? ? ? ? ?Log.d(LOG_VOZ, "Transmiss?o realizada com sucesso...");?
? ? ? ? ? ? ? ?Log.d(LOG_VOZ, "Fechando a conex?o...");?
? ? ? ? ? ? ? ?conexao.close();?
? ? ? ? ? ? ? ?socket.close();?
? ? ? ? ? ? ? ?Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso ==============");?
? ? ? ? ? } catch (IOException e) {?
? ? ? ? ? ? ? ?Log.e(LOG_VOZ, "Erro ao fazer a conex?o via Socket. " + e.getMessage());?
? ? ? ? ? ? ? ?// TODO Auto-generated catch block?
? ? ? ? ? }?
? ? }?
?
}?
?
? ? class SocketOpener implements Runnable {?
?
? ? ?private String host;?
? ? ?private int porta;?
? ? ?private Socket socket;?
?
? ? ?public SocketOpener(String host, int porta) {?
? ? ? ? ? this.host = host;?
? ? ? ? ? this.porta = porta;?
? ? ? ? ? socket = null;?
? ? ?}?
?
? ? ?public static Socket openSocket(String host, int porta, int timeOut) {?
?
? ? ? ? ? SocketOpener opener = new SocketOpener(host, porta);?
? ? ? ? ? Thread t = new Thread(opener);?
? ? ? ? ? t.start();?
? ? ? ? ? try {?
? ? ? ? ? ? ? ?t.join(timeOut);?
? ? ? ? ? } catch(InterruptedException e) {?
? ? ? ? ? ? ? ?Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage());?
? ? ? ? ? ? ? ?//TODO: Mensagem informativa?
? ? ? ? ? ? ? ?return null;?
? ? ? ? ? }?
? ? ? ? ? return opener.getSocket();?
? ? ?}?
?
? ? ?public void run() {?
? ? ? ? ? try {?
? ? ? ? ? ? ? ?socket = new Socket(host, porta);?
?
? ? ? ? ? }catch(IOException e) {?
? ? ? ? ? ? ? ?Log.e(Reconhecimento.LOG_VOZ, "Erro na cria??o do socket. " + e.getMessage());?
? ? ? ? ? ? ? ?//TODO: Mensagem informativa?
? ? ? ? ? }?
? ? ?}?
?
? ? ?public Socket getSocket() {?
? ? ? ? ? return socket;?
? ? ?}?
?
计算机上

import java.io.BufferedReader;?
import java.io.DataInputStream;?
import java.io.DataOutputStream;?
import java.io.File;?
import java.io.FileOutputStream;?
import java.io.IOException;?
import java.io.InputStreamReader;?
import java.net.ServerSocket;?
import java.net.Socket;?
?
public class ServidorArquivo {?
?
? ? ?private static int porta = 5158;?
?
? ? ?static String ARQUIVO = "voz.amr";?
? ? ?/**?
? ? ? * Caminho que será gravado o arquivo de audio?
? ? ? */?
? ? ?static String PATH = "/home/iade/Trabalho/lib/";?
?
? ? ?public static void main(String[] args) {?
?
? ? ? ? ? int i = 1;?
? ? ? ? ? try {?
? ? ? ? ? ? ? ?System.out.println("Iniciando o Servidor Socket - Android.");?
? ? ? ? ? ? ? ?ServerSocket s = new ServerSocket(porta);?
? ? ? ? ? ? ? ?System.out.println("Servidor Iniciado com Sucesso...");?
? ? ? ? ? ? ? ?System.out.println("Aguardando conex?es na porta: " + porta);?
? ? ? ? ? ? ? ?while(true) {?
? ? ? ? ? ? ? ? ? ? Socket recebendo = s.accept();?
? ? ? ? ? ? ? ? ? ? System.out.println("Aceitando conex?o de no " + i);?
? ? ? ? ? ? ? ? ? ? new ThreadedHandler(recebendo).start();?
? ? ? ? ? ? ? ? ? ? i++;?
? ? ? ? ? ? ? ?}?
? ? ? ? ? ? ? ?} catch (Exception e) {?
? ? ? ? ? ? ? ? ? ? System.out.println("Erro: " + e.getMessage());?
? ? ? ? ? ? ? ? ? ? e.printStackTrace();?
? ? ? ? ? ? ? ?}?
? ? ?}?
?
}?
?
class ThreadedHandler extends Thread {?
?
? ? ?private Socket socket;?
?
? ? ?public ThreadedHandler(Socket so) {?
? ? ? ? ? socket = so;?
? ? ?}?
?
? ? ?public void run() {?
?
? ? ? ? ? DataInputStream entrada = null;?
? ? ? ? ? DataOutputStream arquivo = null;?
? ? ? ? ? try {?
?
? ? ? ? ? ? ? ?entrada = new DataInputStream(socket.getInputStream());?
? ? ? ? ? ? ? ?System.out.println("========== Iniciando a leitura dos dados via Sockets ==========");?
? ? ? ? ? ? ? ?long tamanho = entrada.readLong();?
? ? ? ? ? ? ? ?System.out.println("Tamanho do vetor " + tamanho);?
? ? ? ? ? ? ? ?File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO);?
? ? ? ? ? ? ? ?if(!file.exists())?
? ? ? ? ? ? ? ? ? ? file.createNewFile();?
?
? ? ? ? ? ? ? ?arquivo = new DataOutputStream(new FileOutputStream(file));?
? ? ? ? ? ? ? ?for(int j = 0; j < tamanho; j++) {?
? ? ? ? ? ? ? ? ? ? arquivo.write(entrada.readByte());?
? ? ? ? ? ? ? ?}?
? ? ? ? ? ? ? ?System.out.println("========== Dados recebidos com sucesso ==========");?
?
? ? ? ? ? } catch (Exception e) {?
? ? ? ? ? ? ? ?System.out.println("Erro ao tratar do socket: " + e.getMessage());?
? ? ? ? ? ? ? ?e.printStackTrace();?
? ? ? ? ? } finally {?
? ? ? ? ? ? ? ?System.out.println("**** Fechando as conex?es ****");?
? ? ? ? ? ? ? ?try {?
? ? ? ? ? ? ? ? ? ? entrada.close();?
? ? ? ? ? ? ? ? ? ? socket.close();?
? ? ? ? ? ? ? ? ? ? arquivo.close();?
? ? ? ? ? ? ? ?} catch (IOException e) {?
? ? ? ? ? ? ? ? ? ? System.out.println("Erro ao fechar conex�es " + e.getMessage());?
? ? ? ? ? ? ? ? ? ? e.printStackTrace();?
? ? ? ? ? ? ? ?}?
?
? ? ? ? ? }?
? ? ? ? ? System.out.println("============= Fim da Grava??o ===========");?
?
? ? ? ? ? // tratar o arquivo?
?
? ? ? ? ? String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav";?
? ? ? ? ? String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100";?
? ? ? ? ? String dir = "/home/iade/Trabalho/lib";?
? ? ? ? ? File workDir = new File(dir);?
? ? ? ? ? File f1 = new File(dir+"/voz.wav");?
? ? ? ? ? File f2 = new File(dir+"/voz2.wav");?
? ? ? ? ? f1.delete();?
? ? ? ? ? f2.delete();?
?
? ? ? ? ? try {?
? ? ? ? ? ? ? ?executeCommand(cmd1, workDir);?
? ? ? ? ? ? ? ?System.out.println("realizo

读书人网 >移动开发

热点推荐