Reproduction of raw PCM sound received in UDP packets

The remote device sends live raw PCM audio (without a header) to UDP packets, and I need to implement a program in java to receive these packets and play them on a PC in real time. Since I know that the original PCM attributes are 16 bits, mono, 24 kHz sampling rate, so I tried to add the wav header to this raw PCM sound and playback, but the problem is that I don't have the audio file size.

I also implemented a program based on this link , but it only gives noise in the output.

I have to use UDP, and I can only get raw PCM from a remote device, so is it their library or API with which I can play this raw audio on a PC?

+4
source share
1 answer

Here is a simple example to get the output string and play PCM. At startup, it plays a second long annoying beep.

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class RawAudioPlay {

    public static void main(String[] args) {
        try {
            // select audio format parameters
            AudioFormat af = new AudioFormat(24000, 16, 1, true, false);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
            SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

            // generate some PCM data (a sine wave for simplicity)
            byte[] buffer = new byte[64];
            double step = Math.PI / buffer.length;
            double angle = Math.PI * 2;
            int i = buffer.length;
            while (i > 0) {
                double sine = Math.sin(angle);
                int sample = (int) Math.round(sine * 32767);
                buffer[--i] = (byte) (sample >> 8);
                buffer[--i] = (byte) sample;
                angle -= step;
            }

            // prepare audio output
            line.open(af, 4096);
            line.start();
            // output wave form repeatedly
            for (int n=0; n<500; ++n) {
                line.write(buffer, 0, buffer.length);
            }
            // shut down audio
            line.drain();
            line.stop();
            line.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}

, , - " PCM", , PCM - . AudioFormat, / endian, PCM , , .

+5

Source: https://habr.com/ru/post/1609688/


All Articles