Sending audio stream over TCP, UnsupportedAudioFileException

前端 未结 2 847
北恋
北恋 2021-01-04 19:13

I have succeeded with sending and reading text and images data over TCP sockets. But I am unable to sending and reading audio stream data.

sample code at server:

2条回答
  •  余生分开走
    2021-01-04 19:51

    The bytes will be received completely as TCP is reliable. There is another small issue. You need to play the received audio from the audio stream, only creating an audio input stream will not play it. There can be different possible techniques for playing the audio received. You can use a Clip or SourceDataLine from the Java Sound API. Also, do not create the AudioInputStream multiple times. Simply create it once and use it.

    Here's one of the possible solution you can use for playing the received audio.

    public class RDPPlayAudioBytes {
    
    private static Socket socket;
    private static BufferedInputStream inputStream;
    
    /**
     * @param args
     * @throws javax.sound.sampled.LineUnavailableException
     */
    public static void main(String[] args) throws LineUnavailableException {
        // TODO Auto-generated method stub
        // SocketAddress socketAddress = new InetSocketAddress("172.19.1.50", 4444);
        try {
            socket = new Socket("127.0.0.1", 6666);
    
            if (socket.isConnected()) {
    
                inputStream = new BufferedInputStream(socket.getInputStream());
    
                Clip clip = AudioSystem.getClip();
                AudioInputStream ais = AudioSystem.getAudioInputStream(inputStream);
                clip.open(ais);
                clip.start();
    
                while (inputStream != null) {
                    if (clip.isActive()) {
    
                        System.out.println("********** Buffred *********" + inputStream.available());
    
                    }
                }
    
            }
    
        } catch (IOException | UnsupportedAudioFileException e) {
            System.err.println(e);
        }
    }
    }
    

    You may need a different implementation based on your requirement. This is just a demonstration on how you can use the AudioInputStream for playing audio using Clip. You may notice quite a few changes in the code I have posted. I hope you understand this well.

    You may refer the Java Sound API docs to dive into the basics of playing audio.

    NOTE:

    1. Just for your knowledge, you may need to implement a listener so that the program do not get closed before the audio clip finishes playing. In the current implementation it won't happen due to the loop used. But it is better to use a listener. You may refer this post.

    2. You can also read the audio data into byte[] and then play it as soon as it is received. The implementation would change slightly.

提交回复
热议问题