androidstreampcmaudiotrack

Cannot play PCM stream with Encoding ENCODING_PCM_FLOAT


I know that there are a lot of questions about this topic. But I'm having issue with ENCODING_PCM_FLOAT.

I have an PCM stream with following information:

Encoding : 32 bit float
Byte order: Little Endian
Channels : 2 channels ( stereo)
Sample Rate : 48000

And I want to feed it to AudioTrack. I use the following APIs:

private final int SAMPLE_RATE = 48000;
private final int CHANNEL_COUNT = AudioFormat.CHANNEL_OUT_STEREO;
private final int ENCODING = AudioFormat.ENCODING_PCM_FLOAT;
...
int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNEL_COUNT, ENCODING);    
AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_MEDIA)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build();
AudioFormat audioFormat = new AudioFormat.Builder()
    .setEncoding(ENCODING)
    .setSampleRate(SAMPLE_RATE)
    .build();
audioTrack = new AudioTrack(audioAttributes, audioFormat, bufferSize
    , AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE);
audioTrack.play();

And then I start listening from audio stream:

    private void startListening() {
        while (true) {
            try {
                byte[] buffer = new byte[8192];

                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                mSocket.receive(packet);

                FloatBuffer floatBuffer = ByteBuffer.wrap(packet.getData()).asFloatBuffer();
                float[] audioFloats = new float[floatBuffer.capacity()];
                floatBuffer.get(audioFloats);

                for (int i = 0; i < audioFloats.length; i++) {
                    audioFloats[i] = audioFloats[i] / 0x8000000;
                }

                audioTrack.write(audioFloats, 0, audioFloats.length, AudioTrack.WRITE_NON_BLOCKING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

But I don't hear any sound at all. I can play the byte array as PCM_16 (without convert it to float array), but it contains so much noise. So I think the stream input is not the problem.

If you have any idea, please let me know.

Thanks for reading!


Solution

  • for (int i = 0; i < audioFloats.length; i++) {
        audioFloats[i] = audioFloats[i] / 0x8000000;
    }
    

    I was an idiot, the code block above is not needed. After removed, the audio play normally.