可以通过以下步骤实现:
ByteBuffer byteBuffer = ByteBuffer.allocate(floatBuffer.length * 4);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
for (float value : floatBuffer) {
byteBuffer.putFloat(value);
}
byte[] audioData = byteBuffer.array();
short numChannels = 1; // 单声道
int sampleRate = 44100; // 采样率
short bitsPerSample = 16; // 采样位数
int byteRate = sampleRate * numChannels * bitsPerSample / 8;
short blockAlign = (short) (numChannels * bitsPerSample / 8);
byte[] header = new byte[44];
header[0] = 'R'; // RIFF标识
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (audioData.length + 36); // 文件长度
header[5] = (byte) ((audioData.length + 36) >> 8);
header[6] = (byte) ((audioData.length + 36) >> 16);
header[7] = (byte) ((audioData.length + 36) >> 24);
header[8] = 'W'; // WAVE标识
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // fmt标识
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // fmt块长度
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // 音频格式(1表示PCM)
header[21] = 0;
header[22] = numChannels; // 声道数
header[23] = 0;
header[24] = (byte) (sampleRate & 0xff); // 采样率
header[25] = (byte) ((sampleRate >> 8) & 0xff);
header[26] = (byte) ((sampleRate >> 16) & 0xff);
header[27] = (byte) ((sampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff); // 数据传输速率
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = blockAlign; // 数据块对齐单位
header[33] = 0;
header[34] = bitsPerSample; // 采样位数
header[35] = 0;
header[36] = 'd'; // data标识
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (audioData.length & 0xff); // 音频数据长度
header[41] = (byte) ((audioData.length >> 8) & 0xff);
header[42] = (byte) ((audioData.length >> 16) & 0xff);
header[43] = (byte) ((audioData.length >> 24) & 0xff);
try {
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(header);
fos.write(audioData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
完成以上步骤后,FloatArray音频缓冲区将被保存为Android上的wav文件。
领取专属 10元无门槛券
手把手带您无忧上云