PAGUE 6 MESES
LEVE 12 MESES
GARANTIR DESCONTO

Fórum Envio de Audio por socket java #493115

22/09/2014

0

Boa tarde sou novo no fórum e estou com um problema no meu tcc.
Estou desenvolvendo um chat com envio de voz mas não estou conseguindo envia, apenas grava a voz e salva em uma pasta mas não envia, alguém por favor me ajude?!
Segue abaixo as classes.

ChatCliente
package Socket;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatCliente extends JFrame {

	private static final long serialVersionUID = -722779439625841540L;
	JTextField textoParaEnviar;
	PrintWriter escritor;
	Socket socket;
	String nome;
	JTextArea textoRecebido;
	Scanner leitor;
	JButton btnVoz, btncam;

	private class EscutaServidor implements Runnable {

		@Override
		public void run() {

			try {

				String texto;
				while ((texto = leitor.nextLine()) != null) {
					textoRecebido.append(texto + "\n");
				}

			} catch (Exception x) {
				throw new RuntimeException();
			}

		}

	}

	public ChatCliente(String nome) {

		super("Chat : " + nome);
		this.nome = nome;

		Font fonte = new Font("Serif", Font.PLAIN, 15);
		textoParaEnviar = new JTextField();
		textoParaEnviar.setFont(fonte);
		JButton botao = new JButton("Enviar");
		botao.setFont(fonte);
		botao.addActionListener(new EnviarListener());
		getRootPane().setDefaultButton(botao);

		btnVoz = new JButton("Audio");
		btnVoz.setFont(fonte);
		btnVoz.addActionListener(new chamadaDeVoz());

		btncam = new JButton("Video");
		btncam.setFont(fonte);
		btncam.addActionListener(new Cam());

		/*
		 * btnVozParar = new JButton("Parar"); btnVozParar.setFont(fonte);
		 * btnVozParar.addActionListener(new pararChamadaDeVoz());
		 */

		Container envio = new JPanel();
		envio.setLayout(new BorderLayout());
		envio.add(BorderLayout.CENTER, textoParaEnviar);
		envio.add(BorderLayout.EAST, botao);
		envio.add(BorderLayout.EAST, btnVoz);
		envio.add(BorderLayout.SOUTH, btncam);
		// envio.add(BorderLayout.SOUTH, btnVozParar);
		getContentPane().add(BorderLayout.SOUTH, envio);

		textoRecebido = new JTextArea();
		textoRecebido.setFont(fonte);
		JScrollPane scroll = new JScrollPane(textoRecebido);

		textoRecebido.setEditable(false);
		getContentPane().add(BorderLayout.CENTER, scroll);
		getContentPane().add(BorderLayout.SOUTH, envio);

		configurarRede();

		setSize(500, 500);
		setVisible(true);

	}

	private class EnviarListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {

			escritor.println(nome + " : " + textoParaEnviar.getText());
			escritor.flush();
			textoParaEnviar.setText("");
			textoParaEnviar.requestFocus();

		}

	}

	private void configurarRede() {
		try {
			socket = new Socket("127.0.0.1", 3000);
			escritor = new PrintWriter(socket.getOutputStream());
			leitor = new Scanner(socket.getInputStream());
			new Thread(new EscutaServidor()).start();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		new ChatCliente("Ricardo");
		new ChatCliente("Sandra");

	}

	private class chamadaDeVoz implements ActionListener {

		protected static final long TIMEOUT = 5000;
		private BufferedOutputStream bos;

		@Override
		public void actionPerformed(ActionEvent arg0) {

			try {
				JavaSoundRecorder jsr = new JavaSoundRecorder();

				Thread stopper = new Thread(new Runnable() {
					public void run() {
						try {
							Thread.sleep(TIMEOUT);
							jsr.finish();
							transferFile(nome);
							 escritor.println(nome + " : Enviou um som.");
							 escritor.flush();

						} catch (InterruptedException ex) {
							JOptionPane.showMessageDialog(null, "Fudeu!");
							ex.printStackTrace();
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null,
									"Fudeu de novo!");
							e.printStackTrace();
						}
					}
				});
				stopper.start();
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "Fudeu!");
				e.printStackTrace();
			}

		}

		public void transferFile(String filename) throws Exception {

			InputStream is = socket.getInputStream();
			FileOutputStream fos = new FileOutputStream(
					"C:/Users/Jonathan/Desktop/audiosGravados/" + filename
							+ ".wav");
			bos = new BufferedOutputStream(fos);
			byte[] mybytearray = new byte[1024];
			int bytesRead = is.read(mybytearray, 0, mybytearray.length);
			bos.write(mybytearray, 0, bytesRead);

		}

	}

	public class Cam implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			new WebCam();

		}

	}

}


ChatServer
package Socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ChatServer {

	List<PrintWriter> escritores = new ArrayList<>();

	public ChatServer() {

		ServerSocket server;

		try {

			server = new ServerSocket(3000);
			while (true) {
				Socket socket = server.accept();
				new Thread(new EscutaCliente(socket)).start();
				PrintWriter p = new PrintWriter(socket.getOutputStream());
				escritores.add(p);
			}

		} catch (IOException e) {

		}
	}

	private void encaminharParaTodos(String texto) {
		for (PrintWriter w : escritores) {
			try {
				w.println(texto);
				w.flush();
			} catch (Exception e) {
			}
		}
	}

	private class EscutaCliente implements Runnable {

		Scanner leitor;

		public EscutaCliente(Socket socket) {
			try {
				leitor = new Scanner(socket.getInputStream());
			} catch (Exception e) {

			}

		}

		@Override
		public void run() {

			try {
				String texto;
				while ((texto = leitor.nextLine()) != null) {
					System.out.println(texto);
					encaminharParaTodos(texto);

				}
			} catch (Exception x) {
			}

		}

	}

	public static void main(String[] args) {

		new ChatServer();
	}

}


JavaSoundRecorder
package Socket;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class JavaSoundRecorder {
    // record duration, in milliseconds
    static final long RECORD_TIME = 5000;  // 1 minute
 
    // path of the wav file
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    String timestamp = format.format(Calendar.getInstance().getTime());
    File wavFile = new File("C:/Users/Jonathan/Desktop/audiosGravados/"+timestamp+".wav");
   
    
    
    
    // format of audio file
    AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
 
    // the line from which audio data is captured
    TargetDataLine line;
 
    /**
     * Defines an audio format
     */
    AudioFormat getAudioFormat() {
        float sampleRate = 16000;
        int sampleSizeInBits = 8;
        int channels = 2;
        boolean signed = true;
        boolean bigEndian = true;
        AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
                                             channels, signed, bigEndian);
        return format;
    }
 
    /**
     * Captures the sound and record into a WAV file
     */
    String start() {
        try {
            AudioFormat format = getAudioFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
 
            // checks if system supports the data line
            if (!AudioSystem.isLineSupported(info)) {
                System.out.println("Line not supported");
                System.exit(0);
            }
            line = (TargetDataLine) AudioSystem.getLine(info);
            line.open(format);
            line.start();   // start capturing
 
            System.out.println("Start capturing...");
 
            AudioInputStream ais = new AudioInputStream(line);
 
            System.out.println("Start recording...");
 
            // start recording
            AudioSystem.write(ais, fileType, wavFile);
 
        } catch (LineUnavailableException ex) {
            ex.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        
        return timestamp;
    }
 
    /**
     * Closes the target data line to finish capturing and recording
     */
    void finish() {
        line.stop();
        line.close();
        System.out.println("Finished");
    }
 
    /**
     * Entry to run the program
     */
    public static void main(String[] args) {
        final JavaSoundRecorder recorder = new JavaSoundRecorder();
 
        // creates a new thread that waits for a specified
        // of time before stopping
        Thread stopper = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(RECORD_TIME);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                recorder.finish();
            }
        });
 
        stopper.start();
 
        // start recording
        recorder.start();
    }
}


SimpleAudioRecorder
package Socket;

import java.io.IOException;
import java.io.File;

import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.AudioFileFormat;

public class SimpleAudioRecorder extends Thread {
	private TargetDataLine m_line;
	private AudioFileFormat.Type m_targetType;
	private AudioInputStream m_audioInputStream;
	private File m_outputFile;

	public SimpleAudioRecorder(TargetDataLine line,
			AudioFileFormat.Type targetType, File file) {
		m_line = line;
		m_audioInputStream = new AudioInputStream(line);
		m_targetType = targetType;
		m_outputFile = file;
	}

	public void start() {

		m_line.start();

		super.start();
	}

	public void stopRecording() {
		m_line.stop();
		m_line.close();
	}

	public void run() {
		try {
			AudioSystem.write(m_audioInputStream, m_targetType, m_outputFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		if (args.length != 1 || args[0].equals("-h")) {
			printUsageAndExit();
		}

		String strFilename = args[0];
		File outputFile = new File(strFilename);

		AudioFormat audioFormat = new AudioFormat(
				AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F,
				false);

		DataLine.Info info = new DataLine.Info(TargetDataLine.class,
				audioFormat);
		TargetDataLine targetDataLine = null;
		try {
			targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
			targetDataLine.open(audioFormat);
		} catch (LineUnavailableException e) {
			out("unable to get a recording line");
			e.printStackTrace();
			System.exit(1);
		}

		AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;

		SimpleAudioRecorder recorder = new SimpleAudioRecorder(targetDataLine,
				targetType, outputFile);

		out("Press ENTER to start the recording.");
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}

		recorder.start();
		out("Gravando!...");

		out("Press ENTER to stop the recording.");
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}

		recorder.stopRecording();
		out("Recording stopped.");
	}

	private static void printUsageAndExit() {
		out("SimpleAudioRecorder: usage:");
		out("\tjava SimpleAudioRecorder -h");
		out("\tjava SimpleAudioRecorder <audiofile>");
		System.exit(0);
	}

	private static void out(String strMessage) {
		System.out.println(strMessage);
	}
}


Espero que alguém me ajudo, obrigado desde já!
Jonathan Willian

Jonathan Willian

Responder

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar