⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpplay.java

📁 点对点聊天系统 支持文字和语音聊天。同时是服务器和客户端。App.formApp.javaShowMsg.javaTCPClient.javaTCPServer.javaUDPCapture.java
💻 JAVA
字号:
/*
 * UDPPlay.java
 *
 * Created on 2006年5月7日, 下午1:05
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package skyqq;
import javax.sound.sampled.*;
import java.net.*;
/**
 * 接收声音并回放
 * @author wjhua
 */
public class UDPPlay implements Runnable{
    final int bufsize = 16384; //缓存大小   
    SourceDataLine line;
    Thread thread;
    DatagramSocket socket;
    
    byte buffer[] = new byte[1024];
    DatagramPacket pac = new DatagramPacket(buffer , buffer.length);
    /** Creates a new instance of UDPPlay */
    public UDPPlay() {
    }
    public void start() {
        thread = new Thread(this);
        thread.setName("udpplay");
        thread.start();
    }
    
    public void stop() {
        thread = null;
    }
    
    public void run() {
        
        try{
            socket = new DatagramSocket(20001);
            
        } catch(Exception e) {
            System.out.println("Socket Error");
        }
        
        AudioFormat format = new AudioFormat(8000, 16, 2, true, true);
        //audioformat(float samplerate(采样率),
        //int samplesizeinbits, int channels, boolean signed, boolean
        
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        try {
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(format, bufsize);
        } catch (LineUnavailableException ex) {
            return;
        }
        
        int numbytesread = 0;
        line.start();
        
        while (thread != null) {
            try {
                socket.receive(pac);
                numbytesread = pac.getData().length;
                line.write(pac.getData(), 0, numbytesread);
                //write(byte[] b, int off, int len)
                //Writes audio data to the mixer via this source data line
            } catch (Exception e) {
                break;
            }
        }
        
        if (thread != null) {
            line.drain();
        }
        
        line.stop();
        line.close();
        line = null;
    }
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -