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

📄 voicereceive.java

📁 使用java语言写的聊天工具
💻 JAVA
字号:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;

public class VoiceReceive implements Runnable
{
	final static int BUFSIZE=512;
	byte dataBuf[]=new byte[BUFSIZE];
	int RemotePort=0;
	InetAddress RemoteHost=null;
	DatagramSocket UDPClientSocket;
	DatagramPacket ClientPacket=null;
	AudioFormat format = null;
	Thread t = null;
	TargetDataLine tdLine = null;
	SourceDataLine sdLine = null;
	DataLine.Info inInfo = null;
	DataLine.Info outInfo=null;
	
	VoiceReceive()throws  LineUnavailableException, SecurityException
	{   
		 format  = new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED, 8000F, 8, 1,1, 8000F, true);
		 inInfo = new javax.sound.sampled.DataLine.Info(TargetDataLine.class, format);
		 t = null;
		 outInfo = new DataLine.Info(SourceDataLine.class,format);
	}	

	void outPutSound(byte[] bytes)
	{
		DataLine.Info dlInfo = new DataLine.Info(Clip.class,format, bytes.length);
		 try 
		 {
			 Clip clip = (Clip) AudioSystem.getLine(dlInfo);
			 clip.open(format,bytes,0,bytes.length);
			 clip.start();
		 } catch (LineUnavailableException e) 
		 {
			 e.printStackTrace();
		 }
	}
	
	byte[] receive() 
	{
	
		try 
		{
			try 
			 {
			
				UDPClientSocket=new DatagramSocket(3333);
			 } catch (SocketException e) 
			 {
				e.printStackTrace();
			 }
			ClientPacket=new DatagramPacket(dataBuf,BUFSIZE);			
			UDPClientSocket.receive(ClientPacket);
			UDPClientSocket.close();
			UDPClientSocket=null;
		} 
		catch (NullPointerException e) 
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		return(dataBuf);
	
	}	
	
	public void start()
	{
	  t = new Thread(this);
	  t.start();
	 }
	 public void stop()
   {
	  t = null;
   }
   		
	public void run() 
	{
		Thread thisThread = Thread.currentThread();
		try 
		{
			VoiceReceive vr = new VoiceReceive();
			while(t==thisThread)
			{
				byte[] inbyte=vr.receive();
				vr.outPutSound(inbyte);
			}			
		} 
		catch (SecurityException e) 
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} 
		catch (LineUnavailableException e) 
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}		
	}
}

⌨️ 快捷键说明

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