我试图将原始音频数据从一种格式转换为另一种格式以进行语音识别。
20ms
个格式从Discord服务器收到,格式为:48Khz, 16-bit stereo signed BigEndian PCM
。InputStream
中的音频视为RIFF (little-endian) WAVE audio, 16-bit, mono 16,000Hz
音频数据以byte[]
收到,长度为3840
。此byte[]
数组包含上述格式1的20ms
音频。这意味着此音频的1秒为3840 * 50
,即192,000
。这样每秒192,000
个样本。这是有意义的,48KHz
采样率,乘以2(96K样本),因为一个字节是8位,而我们的音频是16位,并且是立体声的另外两个。所以48,000 * 2 * 2 = 192,000
。
因此,每次收到音频数据包时,我都会先调用此方法:
private void addToPacket(byte[] toAdd) {
if(packet.length >= 576000 && !done) {
System.out.println("Processing needs to occur...");
getResult(convertAudio());
packet = null; // reset the packet
return;
}
byte[] newPacket = new byte[packet.length + 3840];
// copy old packet onto new temp array
System.arraycopy(packet, 0, newPacket, 0, packet.length);
// copy toAdd packet onto new temp array
System.arraycopy(toAdd, 0, newPacket, 3840, toAdd.length);
// overwrite the old packet with the newly resized packet
packet = newPacket;
}
这只会将新数据包添加到一个大字节[],直到byte []包含3秒的音频数据(576,000个样本,或192000 * 3)。 3秒的音频数据是足够的时间(只是一个猜测)来检测用户是否说机器人的激活热词,例如"嘿,计算机。"。以下是我如何转换声音数据:
private byte[] convertAudio() {
// STEP 1 - DROP EVERY OTHER PACKET TO REMOVE STEREO FROM THE AUDIO
byte[] mono = new byte[96000];
for(int i = 0, j = 0; i % 2 == 0 && i < packet.length; i++, j++) {
mono[j] = packet[i];
}
// STEP 2 - DROP EVERY 3RD PACKET TO CONVERT TO 16K HZ Audio
byte[] resampled = new byte[32000];
for(int i = 0, j = 0; i % 3 == 0 && i < mono.length; i++, j++) {
resampled[j] = mono[i];
}
// STEP 3 - CONVERT TO LITTLE ENDIAN
ByteBuffer buffer = ByteBuffer.allocate(resampled.length);
buffer.order(ByteOrder.BIG_ENDIAN);
for(byte b : resampled) {
buffer.put(b);
}
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.rewind();
for(int i = 0; i < resampled.length; i++) {
resampled[i] = buffer.get(i);
}
return resampled;
}
最后,尝试识别这个演讲:
private void getResult(byte[] toProcess) {
InputStream stream = new ByteArrayInputStream(toProcess);
recognizer.startRecognition(stream);
SpeechResult result;
while ((result = recognizer.getResult()) != null) {
System.out.format("Hypothesis: %s\n", result.getHypothesis());
}
recognizer.stopRecognition();
}
我遇到的问题是CMUSphinx
没有崩溃或提供任何错误消息,它每隔3秒就会出现一个空假设。我不确定为什么,但我的猜测是我没有正确转换声音。有任何想法吗?任何帮助将不胜感激。
答案 0 :(得分:0)
因此,有一个更好的内部解决方案,用于转换来自byte[]
的音频。
以下我发现的效果非常好:
// Specify the output format you want
AudioFormat target = new AudioFormat(16000f, 16, 1, true, false);
// Get the audio stream ready, and pass in the raw byte[]
AudioInputStream is = AudioSystem.getAudioInputStream(target, new AudioInputStream(new ByteArrayInputStream(raw), AudioReceiveHandler.OUTPUT_FORMAT, raw.length));
// Write a temporary file to the computer somewhere, this method will return a InputStream that can be used for recognition
try {
AudioSystem.write(is, AudioFileFormat.Type.WAVE, new File("C:\\filename.wav"));
} catch(Exception e) {}