无法使用编码ENCODING_PCM_FLOAT播放PCM流

时间:2019-10-25 09:33:23

标签: android stream pcm audiotrack

我知道有关此主题有很多问题。但是我在使用ENCODING_PCM_FLOAT时遇到问题。

我有一个具有以下信息的PCM流:

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

我想将其提供给AudioTrack。我使用以下API:

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();

然后我开始从音频流中收听:

    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();
            }
        }
    }

但是我什么都听不到。我可以将字节数组播放为PCM_16(无需将其转换为浮点数组),但其中包含很多噪音。因此,我认为流输入不是问题。

如果您有任何想法,请告诉我。

感谢阅读!

1 个答案:

答案 0 :(得分:0)

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

我是个白痴,不需要上面的代码块。删除后,音频将正常播放。