将float []转换为AudioTrack的字节数组转换

时间:2019-05-31 09:12:35

标签: java android audiotrack

我正在使用AudioTrack播放一些浮点值。

代码:

float[] audio_payload = getFloatValues();
final int length = audio_payload.length;

int PLAYER_MODE = AudioTrack.MODE_STREAM;
int PLAYER_STREAM_TYPE = AudioManager.STREAM_MUSIC;
int PLAYER_FORMAT = AudioFormat.ENCODING_PCM_FLOAT;
int PLAYER_CONF = AudioFormat.CHANNEL_OUT_MONO;

int PLAYER_SR = 44100;
AudioTrack track = new AudioTrack(PLAYER_STREAM_TYPE, PLAYER_SR, PLAYER_CONF, PLAYER_FORMAT, audio_payload.length*4, PLAYER_MODE);
track.write(audio_payload, 0, length, AudioTrack.WRITE_NON_BLOCKING);
track.play();

我的问题是在android 20或更低版本的函数中,不支持track.write(float[], offset, lenghtInBytes, writeMode);Android Developer Docs

如何将我的float值转换为short或bytes数组以进行播放,因为Android API 3级或更高级别支持它们?

我尝试将float数组转换为short数组,但没有成功,转换后,我的原始音频被更改了。当我尝试将float转换为字节数组时,也会发生同样的情况。

我正在研究的项目具有native-lib,因此在C或Java中,将float转换为short或将float转换为字节之间的任何转换都是有帮助的。

我使用的浮动代码的缩写:

public static short floatToShort(float x) {
    if (x < Short.MIN_VALUE) {
        return Short.MIN_VALUE;
    }
    if (x > Short.MAX_VALUE) {
        return Short.MAX_VALUE;
    }
    return (short) Math.round(x);
}

浮动到字节:

public static byte[] convertToByteArray(float value) {
      byte[] bytes = new byte[4];
      ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
      buffer.putFloat(value);
      return buffer.array();

  }

转换后录音机没有播放音频,也看不到任何错误

更新 也尝试过

private short [] floatArrayToShortArray(float [] array) {
    short [] payload = new short[array.length];
    for (int i=0; i<array.length; i++) {
        payload[i] = (short) ((short) array[i] * 32767);
    }
    return payload;

}

但是audioTrack无法播放。

1 个答案:

答案 0 :(得分:1)

通过这种方法,我能够将Float转换为PCM16 short:

/**
 * Used to convert Float to PCM16 short byte array.
 */
private val convertBuffer = ByteBuffer.allocate(2).apply {
    order(ByteOrder.LITTLE_ENDIAN)
}

/**
 * Converts Float to PCM16 short byte buffer.
 * @param value Float value to convert
 * @return PCM16 short byte array from Float value
 */
private fun floatToPcm16(value: Float): ByteArray {
    convertBuffer.clear()
    convertBuffer.putShort((value * 32768F).toShort())
    return convertBuffer.array()
}