音频:在字节数组的样本量变化 [英] Audio: Change Volume of samples in byte array
问题描述
我使用这种方法(如下所示)读取WAV文件为一个字节数组。现在,我已经是存储在我的字节数组里面,我想改变的声音音量。
I'm reading a wav-file to a byte array using this method (shown below). Now that I have it stored inside my byte array, I want to change the sounds volume.
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;
}
编辑:每请求对音频格式的一些信息:
Per request some info on the audio format:
PCM_SIGNED 44100.0赫兹,16位,单声道,2个字节/帧,小尾数
PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian
从物理级的我记得您可以通过正弦值0和1之间的数字乘以改变正弦波的幅度。
From physics-class I remembered that you can change the amplitude of a sine-wave by multiplying the sine-value with a number between 0 and 1.
编辑:更新code 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
与卷
。如果我不和比较两个数组Arrays.compare(数组,audioSample)
我可以断定字节数组被转换为正确int和周围的其他方法
The sound is heavily distorted if I multiply audioSample
with volume
. If I don't and compare both arrays with Arrays.compare(array, audioSample)
I can conclude that the byte-array is being converted correctly to int and the other way around.
任何人可以帮助我吗?我究竟得到什么错在这里?谢谢! :)
Can anybody help me out? What am I getting wrong here? Thank you! :)
推荐答案
您确定您正在阅读的8位单声道音频?否则,一个字节不等于一个样品,你可以不只是规模的每个字节。例如。如果它是16位的数据必须要分析每对字节作为一个16位的整数的,规模是,然后将它写回为两个字节。
Are you sure you're reading 8-bit mono audio? Otherwise one byte does not equal one sample, and you cannot just scale each byte. E.g. if it is 16-bit data you have to parse every pair of bytes as a 16-bit integer, scale that, and then write it back as two bytes.
这篇关于音频:在字节数组的样本量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!