开发者

How to send audio stream via UDP in java?

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 :)


You don't what the Player class here, you want to use the classes in javax.sound.sampled. As far as I can tell Player is for playing a sound, not accessing its contents.

I have not tested this, but try using .read on the TargetDataLine you are creating to fill a buffer, and then sending the buffer to the other host.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜