How to send audio stream via UDP in java?

Posted by Nob Venoda on Stack Overflow See other posts from Stack Overflow or by Nob Venoda
Published on 2010-01-18T01:02:30Z Indexed on 2010/05/26 10:01 UTC
Read the original article Hit count: 658

Filed under:
|
|
|
|

Hi to all :)

I have a problem, i have set MediaLocator to microphone input, and then created Player. I need to grab that sound from the microphone, encode it to some lower quality stream, and send it as a datagram packet via UDP. Here's the code, i found most of it online and adapted it to my app:

public class AudioSender extends Thread {

private MediaLocator ml = new MediaLocator("javasound://44100");
private DatagramSocket socket;
private boolean transmitting;
private Player player;
TargetDataLine mic;
byte[] buffer;
private AudioFormat format;


private DatagramSocket datagramSocket(){
    try {
        return new DatagramSocket();
    } catch (SocketException ex) {
        return null;
    }
}

private void startMic() {
    try {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        mic = (TargetDataLine) AudioSystem.getLine(info);
        mic.open(format);
        mic.start();
        buffer = new byte[1024];
    } catch (LineUnavailableException ex) {
        Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private Player createPlayer() {
    try {
        return Manager.createRealizedPlayer(ml);
    } catch (IOException ex) {
        return null;
    } catch (NoPlayerException ex) {
        return null;
    } catch (CannotRealizeException ex) {
        return null;
    }
}

private void send() {
    try {
        mic.read(buffer, 0, 1024);
        DatagramPacket packet = 
            new DatagramPacket(
                buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91);
        socket.send(packet);
    } catch (IOException ex) {
        Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@Override
public void run() {
    player = createPlayer();
    player.start();
    socket = datagramSocket();
    transmitting = true;
    startMic();
    while (transmitting) {
        send();
    }  
}

public static void main(String[] args) {
    AudioSender as = new AudioSender();
    as.start();
}

}

And only thing that happens when I run the receiver class, is me hearing this Player from the sender class. And I cant seem to see the connection between TargetDataLine and Player. Basically, I need to get the sound form player, and somehow convert it to bytes[], therefore I can sent it as datagram. Any ideas? Everything is acceptable, as long as it works :)

© Stack Overflow or respective owner

Related posts about java

Related posts about audio