python将numpy.ndarray转为音频文件wav,只需要几行代码。
import soundfile as sf
sf.write("out.wav", arr, samplerate=24000) #arr为numpy.ndarray
java要是完成类似的功能就比较复杂。我把浮点数保存在了txt文件中,首先通过java读取txt并转为float[],之后转为wav,具体代码如下:
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
public class test_local {
public static void main(String[] args) throws Exception {
String filePath = "array.txt";
String wavPath = "out.wav";
float[] buffer = new float[71700];
int index = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
float value = Float.parseFloat(line);
buffer[index++] = value;
}
} catch (IOException e) {
e.printStackTrace();
}
// 上面的代码仅仅是为了从txt中获取浮点数
final byte[] byteBuffer = new byte[buffer.length * 2];
int bufferIndex = 0;
for (int i = 0; i < byteBuffer.length; i++) {
final int x = (int)(buffer[bufferIndex++] * 32767.0);
byteBuffer[i++] = (byte)x;
byteBuffer[i] = (byte)(x >>> 8);
}
File out = new File(wavPath);
final boolean bigEndian = false;
final boolean signed = true;
double sampleRate = 24000.0; //控制速度
final int bits = 16;
final int channels = 1;
AudioFormat format = new AudioFormat((float)sampleRate, bits, channels, signed, bigEndian);
ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer);
AudioInputStream audioInputStream = new AudioInputStream(bais, format, buffer.length);
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
audioInputStream.close();
}
}
我存浮点数的txt如下,存了71700个数: