java语音聊天程序集成了java文本聊天和java语音聊天

java语音聊天程序集成了java文本聊天和java语音聊天。

///服务器界面

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class Server extends Frame
{
    TextField tf=new TextField(20);
    TextArea ta=new TextArea();
    Button send=new Button("send");
    Button voiceChat=new Button("voiceChat");
    ServerSocket serSocket;
    Socket client;
    InputStream in;
    BufferedReader br;
    OutputStream out;
    BufferedWriter bw;
    public Server()
    {
        super("Server");
        add("North",tf);
        add("Center",ta);
        add("South",send);
        add("East",voiceChat);
        setBackground(Color.yellow);
        setSize(250,250);
        show();
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                dispose();
                System.exit(0);
            }
        }
        );
        try
        {
            ServerSocket serSocket=new ServerSocket(5000);
            client=serSocket.accept();
            ta.append("client host"+client.getInetAddress().getHostName()+"\n\n");
            in=client.getInputStream();
            br=new BufferedReader(new InputStreamReader(in));
            out=client.getOutputStream();
            bw=new BufferedWriter(new OutputStreamWriter(out));
        }
        catch(Exception e)
        {
        }
        while(true)
        {
            try
            {
                byte[] buf=new byte[200];
                in.read(buf);
                String str=new String(buf);
                ta.append("Client say:"+str);
                ta.append("\n");
            }
            catch(IOException e)
            {
            }
        }
    }
    public boolean action(Event evt, Object arg)
    {
        if(evt.target.equals(send))
        {
            try
            {
                String str=tf.getText();
                byte[] buf=str.getBytes();
                tf.setText(null);
                out.write(buf);
                ta.append("I say:"+str);     ta.append("\n");
            }
            catch(IOException ioe)
            {
            }
        }
        else if(evt.target.equals(voiceChat))
        {
            try
            {
                ServerSocket serSock=new ServerSocket(6000);
                Socket cli=serSock.accept();
                Playback player=new Playback(cli);
                player.start();
            }
            catch(Exception e)
            {
            }
        }
        return true;
        
    }
    
    public static void main(String[] args)
    {
        Server server=new Server();
    }
}

//客户端界面

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Client extends Frame
{
    TextField tf=new TextField(20);
    TextArea ta=new TextArea();
    Button send=new Button("send");
    Button voiceChat=new Button("voiceChat");
    Socket client;
    InputStream in;
    OutputStream out;
    BufferedReader br;
    BufferedWriter bw;
    public Client()
    {
        super("Client");
        add("North",tf);
        add("Center",ta);
        add("South",send);
        add("East",voiceChat);
        setSize(250,250);
        show();
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                dispose();
                System.exit(0);
            }
        });
        try
        {
            Socket client=new Socket("127.0.0.1",5000);
            ta.append("Connect to:"+client.getInetAddress().getHostName()+"\n\n");
            in=client.getInputStream();
            br=new BufferedReader(new InputStreamReader(in));
            out=client.getOutputStream();
            bw=new BufferedWriter(new OutputStreamWriter(out));
        }
        catch(IOException ioe)
        {}
        while(true)
        {
            try
            {
                byte[] buf=new byte[200];
                in.read(buf);
                String str=new String(buf);
                ta.append("Server say:"+str);
                ta.append("\n");
            }
            catch(IOException e)
            {
                System.out.print(e.getMessage());
            }
        }
    }
    public boolean action(Event evt, Object arg)
    {
        if(evt.target.equals(send))
        {
            try
            {
                String str=tf.getText();
                byte[] buf=str.getBytes();
                tf.setText(null);
                out.write(buf);
                ta.append("I say:"+str);
                ta.append("\n");
            }
            catch(IOException ioe)
            {
                System.out.print(ioe.getMessage());
            }
        }
        else if(evt.target.equals(voiceChat))
        {
            try
            {
                Socket cli=new Socket("127.0.0.1",6000);
                Capture cap=new Capture(cli);
                cap.start();
            }
            catch(Exception e)
            {}
        }
        return true;
    }
    public static void main(String[] args)
    {
        Client client=new Client();
    }
    
}

//音频捕获部分,
//Capture.java
import java.io.*; 
import javax.sound.sampled.*; 
import java.net.*;

/** 
* Title:        VoiceChat 
* Description: 音频捕捉(录音程序) 
* Copyright:    Copyright (c) 2001 
* Company: 
* @author        
* @version 1.0 
*/

class Capture implements Runnable {

       TargetDataLine line; 
       Thread thread; 
       Socket s; 
       BufferedOutputStream captrueOutputStream;

       Capture(Socket s){//构造器 取得socket以获得网络输出流 
         this.s=s; 
       }

       public void start() {

           thread = new Thread(this); 
           thread.setName("Capture"); 
           thread.start(); 
       }

       public void stop() { 
           thread = null; 
       }

       public void run() {

           try { 
             captrueOutputStream=new BufferedOutputStream(s.getOutputStream());//建立输出流 此处可以加套压缩流用来压缩数据 
           } 
           catch (IOException ex) { 
               return; 
           }

           AudioFormat format =new AudioFormat(8000,16,2,true,true);//AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian) 
           DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);

           try { 
               line = (TargetDataLine) AudioSystem.getLine(info); 
               line.open(format, line.getBufferSize()); 
           } catch (Exception ex) { 
               return; 
           }

           byte[] data = new byte[1024];//此处的1024可以情况进行调整,应跟下面的1024应保持一致 
           int numBytesRead=0; 
           line.start();

           while (thread != null) { 
               numBytesRead = line.read(data, 0,128);//取数据(1024)的大小直接关系到传输的速度,一般越小越快, 
               try { 
                 captrueOutputStream.write(data, 0, numBytesRead);//写入网络流 
               } 
               catch (Exception ex) { 
                   break; 
               } 
           }

           line.stop(); 
           line.close(); 
           line = null;

           try { 
               captrueOutputStream.flush(); 
               captrueOutputStream.close(); 
           } catch (IOException ex) { 
               ex.printStackTrace(); 
           } 
       } 
     
}

//下面是音频输出的代码:

//Playback.java
import java.io.*; 
import javax.sound.sampled.*; 
import java.net.*;


/** 
* Title:        VoiceChat 
* Description: 输出音频(放音程序) 
* Copyright:    Copyright (c) 2001 
* Company: 
* @author        
* @version 1.0 
*/


class Playback implements Runnable {

       final int bufSize = 16384; 
       SourceDataLine line; 
       Thread thread; 
       Socket s;

       Playback(Socket s){//构造器 取得socket以获得网络输入流 
         this.s=s; 
       } 
       public void start() {

           thread = new Thread(this); 
           thread.setName("Playback"); 
           thread.start(); 
       }

       public void stop() { 
           thread = null; 
       }

       public void run() {

           AudioFormat format =new AudioFormat(8000,16,2,true,true);//AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian) 
           BufferedInputStream playbackInputStream;

           try { 
             playbackInputStream=new BufferedInputStream(new AudioInputStream(s.getInputStream(),format,2147483647));//封装成音频输出流,如果网络流是经过压缩的需在此加套解压流 
           } 
           catch (IOException ex) { 
               return; 
           }

           DataLine.Info info = new DataLine.Info(SourceDataLine.class,format);

           try { 
               line = (SourceDataLine) AudioSystem.getLine(info); 
               line.open(format, bufSize); 
           } catch (LineUnavailableException ex) { 
               return; 
           }

           byte[] data = new byte[1024];//此处数组的大小跟实时性关系不大,可根据情况进行调整 
           int numBytesRead = 0; 
           line.start();

           while (thread != null) { 
              try{ 
                 numBytesRead = playbackInputStream.read(data); 
                 line.write(data, 0,numBytesRead); 
              } catch (IOException e) { 
                   break; 
               } 
           }

           if (thread != null) { 
               line.drain(); 
           }

           line.stop(); 
           line.close(); 
           line = null; 
       } 
}


你可能感兴趣的:(java语音聊天程序集成了java文本聊天和java语音聊天)