java - 将连续字节[]数据发送到Java中的DatagramSocket,DatagramPacket

标签 java sockets datagram

我正在制作一个 Java 桌面应用程序,我在其中录制来自麦克风的语音,并在 LAN 中实时将此语音数据发送到另一个计算机系统,反之亦然。

我可以通过麦克风录制声音并输出到系统中的扬声器。现在使用 UDP 数据报套接字想要做同样的事情,但是 UDP 服务器没有接收到数据流(字节 [])。

这里是代码:VUClient.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.sound.sampled.*;

public class VUClient extends JFrame {

    boolean stopaudioCapture = false;
    ByteArrayOutputStream byteOutputStream;
    AudioFormat adFormat;
    TargetDataLine targetDataLine;
    AudioInputStream InputStream;
    SourceDataLine sourceLine;
    Graphics g;

    public static void main(String args[]) {
        new VUClient();
    }

    public VUClient() {
        final JButton capture =
                new JButton("Capture");
        final JButton stop =
                new JButton("Stop");
        final JButton play =
                new JButton("Playback");

        capture.setEnabled(true);
        stop.setEnabled(false);
        play.setEnabled(false);

        capture.addActionListener(
                new ActionListener() {
                    public void actionPerformed(
                            ActionEvent e) {
                        capture.setEnabled(false);
                        stop.setEnabled(true);
                        play.setEnabled(false);
                        captureAudio();
                    }
                });
        getContentPane().add(capture);

        stop.addActionListener(
                new ActionListener() {
                    public void actionPerformed(
                            ActionEvent e) {
                        capture.setEnabled(true);
                        stop.setEnabled(false);
                        play.setEnabled(true);
                        stopaudioCapture = true;
                        targetDataLine.close();
                    }
                });
        getContentPane().add(stop);

        play.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(
                            ActionEvent e) {
                        playAudio();
                    }
                });
        getContentPane().add(play);

        getContentPane().setLayout(new FlowLayout());
        setTitle("Capture/Playback Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 100);
        getContentPane().setBackground(Color.white);
        setVisible(true);

        g = (Graphics) this.getGraphics();



    }

    private void captureAudio() {
        try {
            adFormat = getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, adFormat);
            targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
            targetDataLine.open(adFormat);
            targetDataLine.start();

            Thread captureThread = new Thread(new CaptureThread());
            captureThread.start();
        } catch (Exception e) {
            StackTraceElement stackEle[] = e.getStackTrace();
            for (StackTraceElement val : stackEle) {
                System.out.println(val);
            }
            System.exit(0);
        }
    }

    private void playAudio() {
        try {
            byte audioData[] = byteOutputStream.toByteArray();
//     System.out.println("byte auto "+byteOutputStream.toString());
            InputStream byteInputStream = new ByteArrayInputStream(audioData);
            AudioFormat adFormat = getAudioFormat();
            InputStream = new AudioInputStream(byteInputStream, adFormat, audioData.length / adFormat.getFrameSize());
            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, adFormat);
            sourceLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
            sourceLine.open(adFormat);
            sourceLine.start();

            Thread playThread = new Thread(new PlayThread());
            playThread.start();


        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }

    private AudioFormat getAudioFormat() {
        float sampleRate = 8000.0F;
        int sampleInbits = 16;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = false;
        return new AudioFormat(sampleRate, sampleInbits, channels, signed, bigEndian);
    }

    class CaptureThread extends Thread {

        byte tempBuffer[] = new byte[10000];

        public void run() {

            byteOutputStream = new ByteArrayOutputStream();
            stopaudioCapture = false;
            try {
                DatagramSocket clientSocket = new DatagramSocket();
//                InetAddress IPAddress = InetAddress.getByName("192.168.64.142");
                InetAddress IPAddress = InetAddress.getByName("localhost");

                while (!stopaudioCapture) {
                    int cnt = targetDataLine.read(tempBuffer, 0, tempBuffer.length);
                    if (cnt > 0) {
                        DatagramPacket sendPacket = new DatagramPacket(tempBuffer, tempBuffer.length, IPAddress, 9876);
                        clientSocket.send(sendPacket);

                        byteOutputStream.write(tempBuffer, 0, cnt);
//                        System.out.print(cnt);
                    }
//                    DatagramPacket sendPacket = new DatagramPacket(byteOutputStream, 10000, IPAddress, 9876);
//                    clientSocket.send(sendPacket);
                }

                byteOutputStream.close();

            } catch (Exception e) {
                System.out.println("CaptureThread::run()" + e);
                System.exit(0);
            }
        }
    }

    class PlayThread extends Thread {

        byte tempBuffer[] = new byte[10000];

        public void run() {
            try {
//                DatagramSocket clientSocket = new DatagramSocket();
//                InetAddress IPAddress = InetAddress.getByName("192.168.64.142");
//                InetAddress IPAddress = InetAddress.getByName("localhost");



                int cnt;
                while ((cnt = InputStream.read(tempBuffer, 0,tempBuffer.length)) != -1) {
                    if (cnt > 0) {
//                        DatagramPacket sendPacket = new DatagramPacket(tempBuffer, tempBuffer.length, IPAddress, 9876);
//                        clientSocket.send(sendPacket);

//                        sourceLine.write(tempBuffer, 0, cnt);
                    }
                }
//                sourceLine.drain();
//                sourceLine.close();
            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
        }
    }    

}// Class End 

VUServer.java

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

public class VUServer {

    ByteArrayOutputStream byteOutputStream;
    AudioFormat adFormat;
    TargetDataLine targetDataLine;
    AudioInputStream InputStream;
    SourceDataLine sourceLine;

    private AudioFormat getAudioFormat() {
        float sampleRate = 8000.0F;
        int sampleInbits = 16;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = false;
        return new AudioFormat(sampleRate, sampleInbits, channels, signed, bigEndian);
    }

    public static void main(String args[]) {
        new VUServer().runVOIP();
    }

    public void runVOIP() {
        try {
            DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[10000];

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
//                String sentence = new String(receivePacket.getData());
                System.out.println("RECEIVED: ");// + sentence);

                try {
                    byte audioData[] = receivePacket.getData();//byteOutputStream.toByteArray();
//     System.out.println("byte auto "+byteOutputStream.toString());
                    InputStream byteInputStream = new ByteArrayInputStream(audioData);
                    AudioFormat adFormat = getAudioFormat();
                    InputStream = new AudioInputStream(byteInputStream, adFormat, audioData.length / adFormat.getFrameSize());
                    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, adFormat);
                    sourceLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
                    sourceLine.open(adFormat);
                    sourceLine.start();

                    Thread playThread = new Thread(new PlayThread());
                    playThread.start();


                } catch (Exception e) {
                    System.out.println(e);
                    System.exit(0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class PlayThread extends Thread {

        byte tempBuffer[] = new byte[10000];

        public void run() {
            try {
                int cnt;
                while ((cnt = InputStream.read(tempBuffer, 0,tempBuffer.length)) != -1) {
                    if (cnt > 0) {
                        sourceLine.write(tempBuffer, 0, cnt);
                    }
                }
                sourceLine.drain();
                sourceLine.close();
            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
        }
    }
}

最佳答案

你这行有问题(

byte[] receiveData = new byte[10000];

)

使尺寸比这大... 我成功了

byte[] receiveData = new byte[90000];

效果很好....

关于java - 将连续字节[]数据发送到Java中的DatagramSocket,DatagramPacket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174202/

相关文章:

java - 按功能打包好不好?

linux - select()和accept()返回点对应的TCP握手阶段

java - 使用 UDP 单播/多播向一组用户发送消息

java - 通过使用 UPnP 发送广播数据包来发现路由器不起作用

java - 在哪里使用数据报流量运行 java exe 文件?

java - UDP 接收和发送的 UDP 数据包有问题吗?

java - 在 OSGi bundle 中加载 ResourceBundle

Java 泛型 - 无限通配符中的真正含义是什么?

java - 无法通过属性或文本跟踪元素

android - 应用未在 Android Studio 的 Profiler 中显示网络 Activity