如何将PCM缓冲区阵列流式传输到Sphinx4识别器?

时间:2018-07-22 10:10:34

标签: cmusphinx sphinx4

我正在尝试一次将正在读取的音频数据流式传输到512个样本到识别器,但是我没有任何运气。我正在使用LibGDX来实现AudioRecorder对象。知道是什么问题吗?我在下面附加了我的代码:

public static void main(String[] args) throws Exception {
    Configuration configuration = new Configuration();
    configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
    configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
    configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
    configuration.setSampleRate(16000);

    StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration);

    public short[] buffer = new short[512];
    byte[] byteBuffer = short2byte(buffer);

    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream(in);
    recognizer.startRecognition(in);

    AudioRecorder recorder = Gdx.audio.newAudioRecorder(16000, true);   // Records samples at 16k sample rate in mono

    while (true) {
        recorder.read(buffer, 0, buffer.length);    // Reads in 16-bit signed PCM values

        byteBuffer = short2byte(buffer);    // Converts short array to byte array

        out.write(byteBuffer, 0, byteBuffer.length);    

        SpeechResult result;
        if ((result = recognizer.getResult()) != null) {
            System.out.println(result.getHypothesis());
        }
    }
}

/** Converts a short into a byte array.
  * @param sVal source value
  * @param bytes array to convert
  * @param bigEndian is big endian
  */
public void toBytes(short sVal, byte[] bytes, boolean bigEndian) {
    if (bigEndian) {
        bytes[0] = (byte) (sVal >> 8);
        bytes[1] = (byte) (sVal & 0xff);
    } else {
        bytes[0] = (byte) (sVal & 0xff);
        bytes[1] = (byte) (sVal >> 8);
    }
}

private byte[] short2byte(short[] shorts) {
    byte[] bytes = new byte[2 * shorts.length];
    byte[] sample = new byte[2];
    for (int i = 0; i < shorts.length; i++) {
        toBytes(shorts[i], sample, true);
        bytes[i * 2 + 1] = sample[0];
        bytes[i * 2] = sample[1];
    }
    return bytes;
}

0 个答案:

没有答案