我可以在下面的函数中读取WAV文件(每个示例8位),并将其复制到另一个文件中。我想使用给定的源文件的总体积
scale
参数,它在[0,1]范围内。我天真的方法是用
规模
再把它转换成字节。我只有一个嘈杂的文件。如何实现逐字节的音量调整?
public static final int BUFFER_SIZE = 10000;
public static final int WAV_HEADER_SIZE = 44;
public void changeVolume(File source, File destination, float scale) {
RandomAccessFile fileIn = null;
RandomAccessFile fileOut = null;
byte[] header = new byte[WAV_HEADER_SIZE];
byte[] buffer = new byte[BUFFER_SIZE];
try {
fileIn = new RandomAccessFile(source, "r");
fileOut = new RandomAccessFile(destination, "rw");
// copy the header of source to destination file
int numBytes = fileIn.read(header);
fileOut.write(header, 0, numBytes);
// read & write audio samples in blocks of size BUFFER_SIZE
int seekDistance = 0;
int bytesToRead = BUFFER_SIZE;
long totalBytesRead = 0;
while(totalBytesRead < fileIn.length()) {
if (seekDistance + BUFFER_SIZE <= fileIn.length()) {
bytesToRead = BUFFER_SIZE;
} else {
// read remaining bytes
bytesToRead = (int) (fileIn.length() - totalBytesRead);
}
fileIn.seek(seekDistance);
int numBytesRead = fileIn.read(buffer, 0, bytesToRead);
totalBytesRead += numBytesRead;
for (int i = 0; i < numBytesRead - 1; i++) {
// WHAT TO DO HERE?
buffer[i] = (byte) (scale * ((int) buffer[i]));
}
fileOut.write(buffer, 0, numBytesRead);
seekDistance += numBytesRead;
}
fileOut.setLength(fileIn.length());
} catch (FileNotFoundException e) {
System.err.println("File could not be found" + e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
} finally {
try {
fileIn.close();
fileOut.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}