0 java audio wav decibel audioformat
public TargetDataLine targetDataLine;
private static AudioFormat getAudioFormat()
{
return new AudioFormat(16000, 16, 2, true, false);
}
AudioFormat a = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, a);
targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
targetDataLine.open(a);
targetDataLine.start();
AudioInputStream ais = new AudioInputStream(targetDataLine);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("record.wav"));
Run Code Online (Sandbox Code Playgroud)
假设一:您希望在录音结束时处理并保存数据。
ByteArrayOutputStream使用ByteArrayOutputStream.write()将数据写入ByteArrayOutputStream为byte[]数组。ByteArrayInputStream使用您的byte[]数组构建使用以下命令生成音频文件AudioSystem.write()
int numBytesRead = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
boolean stopRecording = false;
while (!stopRecording) {
numBytesRead = targetDataLine.read(buffer, 0, buffer.length);
//short[] samples = encodeToSample(buffer, buffer.length);
// process samples - calculate decibels
if (numBytesRead > 0) {
outStream.write(buffer, 0, numBytesRead);
}
}
outStream.close();
byte[] data = outStream.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, a, data.length);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("record.wav"));
Run Code Online (Sandbox Code Playgroud)假设二:您希望连续读取、处理和保存数据。
您需要一个中间类才能转换ByteArrayOutputStream为ByteArrayInputStream. 在后台线程中捕获音频数据,并在另一个线程中处理并在所需数据量可用时保存数据。
编码:您可以对byte[]阵列中的音频样本进行编码。在您的情况下,两个连续的字节产生一个样本。您将陆续获得两个通道的样本。如果您有任何特定于通道的处理,那么您需要分离每个通道的样本。以下代码片段可以帮助您进行编码 -
public static short[] encodeToSample(byte[] srcBuffer, int numBytes) {
byte[] tempBuffer = new byte[2];
int nSamples = numBytes / 2;
short[] samples = new short[nSamples]; // 16-bit signed value
for (int i = 0; i < nSamples; i++) {
tempBuffer[0] = srcBuffer[2 * i];
tempBuffer[1] = srcBuffer[2 * i + 1];
samples[i] = bytesToShort(tempBuffer);
}
return samples;
}
public static short bytesToShort(byte [] buffer) {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.BIG_ENDIAN);
bb.put(buffer[0]);
bb.put(buffer[1]);
return bb.getShort(0);
}
Run Code Online (Sandbox Code Playgroud)
分贝: Db是给定电平与参考电平的对数比。例如,如果您想计算以 dBFS 为单位的 RMS/Peak,以下代码片段可能会对您有所帮助。
public static void calculatePeakAndRms(short [] samples) {
double sumOfSampleSq = 0.0; // sum of square of normalized samples.
double peakSample = 0.0; // peak sample.
for (short sample : samples) {
double normSample = (double) sample / 32767; // normalized the sample with maximum value.
sumOfSampleSq += (normSample * normSample);
if (Math.abs(sample) > peakSample) {
peakSample = Math.abs(sample);
}
}
double rms = 10*Math.log10(sumOfSampleSq / samples.length);
double peak = 20*Math.log10(peakSample / 32767);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3184 次 |
| 最近记录: |