我正在使用 this method (shown below) 将 wav 文件读入字节数组.现在我已将它存储在我的字节数组中,我想更改音量。
private byte[] getAudioFileData(final String filePath) {
byte[] data = null;
try {
final ByteArrayOutputStream baout = new ByteArrayOutputStream();
final File file = new File(filePath);
final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
byte[] buffer = new byte[4096];
int c;
while ((c = audioInputStream.read(buffer, 0, buffer.length)) != -1) {
baout.write(buffer, 0, c);
}
audioInputStream.close();
baout.close();
data = baout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
编辑:根据请求提供一些关于音频格式的信息:
PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian
在物理课上我记得你可以通过将正弦值乘以 0 到 1 之间的数字来改变正弦波的振幅。
编辑:16 位示例的更新代码:
private byte[] adjustVolume(byte[] audioSamples, double volume) {
byte[] array = new byte[audioSamples.length];
for (int i = 0; i < array.length; i+=2) {
// convert byte pair to int
int audioSample = (int) ((audioSamples[i+1] & 0xff) << 8) | (audioSamples[i] & 0xff);
audioSample = (int) (audioSample * volume);
// convert back
array[i] = (byte) audioSample;
array[i+1] = (byte) (audioSample >> 8);
}
return array;
}
如果我将 audioSample
与 volume
相乘,声音会严重失真。如果我不这样做并将两个数组与 Arrays.compare(array, audioSample)
进行比较,我可以得出结论,字节数组正在正确转换为 int,反之亦然。
有人能帮帮我吗?我在这里弄错了什么?谢谢! :)
最佳答案
int类型的问题,java中int的大小为4字节,样本大小为2字节
这个有效的代码:
private byte[] adjustVolume(byte[] audioSamples, float volume) {
byte[] array = new byte[audioSamples.length];
for (int i = 0; i < array.length; i+=2) {
// convert byte pair to int
short buf1 = audioSamples[i+1];
short buf2 = audioSamples[i];
buf1 = (short) ((buf1 & 0xff) << 8);
buf2 = (short) (buf2 & 0xff);
short res= (short) (buf1 | buf2);
res = (short) (res * volume);
// convert back
array[i] = (byte) res;
array[i+1] = (byte) (res >> 8);
}
return array;
}
关于java - 音频:更改字节数组中样本的音量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14485873/