dimanche 19 novembre 2017

How to stream microphone input via UDP to browser?

I would like to stream the audio input of my microphone via a Java web server to a connected HTTP client. Therefore it should be the best idea to use UDP.

How can I realize this idea?

I've already tried to realize this project with a TCP connection:

public void sendResponse() throws Exception {
        AudioFormat format = getAudioFormat();

        DataLine.Info micInfo = new DataLine.Info(TargetDataLine.class, format);
        TargetDataLine mic = (TargetDataLine) AudioSystem.getLine(micInfo);
        mic.open(format);
        mic.start();

        String statusLine = "HTTP/1.1 200 OK" + "\r\n";
        String serverdetails = "Server";
        String contentTypeLine = "Content-Type: audio/mpeg\r\n";
        String contentLengthLine = "Content-Length: " + mic.getBufferSize() + "\r\n";

        outToClient.writeBytes(statusLine);
        outToClient.writeBytes(serverdetails);
        outToClient.writeBytes(contentTypeLine);
        outToClient.writeBytes(contentLengthLine);
        outToClient.writeBytes("Connection: close\r\n");
        outToClient.writeBytes("\r\n");

        int numBytesRead;
        byte[] targetData = new byte[mic.getBufferSize() / 5];

        while (true) {
            numBytesRead = mic.read(targetData, 0, targetData.length);

            if (numBytesRead == -1) break;
            outToClient.write(targetData, 0, numBytesRead);
        }
    }

    public AudioFormat getAudioFormat(){
        float sampleRate = 48000.0F;
        int sampleSizeInBits = 16;
        int channels = 1;

        boolean signed = true;
        boolean bigEndian = false;

        return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    }

Unfortunately, I'm getting the exception: "java.net.SocketException: Broken pipe" at "outToClient.write(targetData, 0, numBytesRead);"




Aucun commentaire:

Enregistrer un commentaire