本文介绍了来自TargetDataLine的声波的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在尝试从麦克风录制声波并在Java中实时显示振幅值。我遇到了Targetdataline,但是我在理解我从中获取数据时遇到了一些麻烦。

Currently I am trying to record a sound wave from a mic and display amplitude values in realtime in Java. I came across Targetdataline but I am having a bit of trouble understanding I get data from it.

来自Oracle的示例代码说明:

Sample code from Oracle states:

line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
ByteArrayOutputStream out  = new ByteArrayOutputStream();
int numBytesRead;
byte[] data = new byte[line.getBufferSize() / 5];

// Begin audio capture.
line.start();

// Here, stopped is a global boolean set by another thread.
while (!stopped) {
// Read the next chunk of data from the TargetDataLine.
numBytesRead =  line.read(data, 0, data.length);

****ADDED CODE HERE*****

// Save this chunk of data.
out.write(data, 0, numBytesRead);
}    

所以我目前正在尝试添加代码来获取幅度值的输入流但是当我在添加的代码行打印变量数据时,我得到了大量的字节。

So I am currently trying to add code to get a input stream of amplitude values however I get a ton of bytes when I print what the variable data is at the added code line.

for (int j=0; j<data.length; j++) {
   System.out.format("%02X ", data[j]);
}

之前使用过TargetDataLine的人是否知道如何使用它?

Does anyone who has used TargetDataLine before know how I can make use of it?

推荐答案

对于将来使用TargetDataLine进行声音提取时遇到问题的人,Ganesh Tiwari的WaveData类包含一个非常有用的方法将字节转换为浮点数组():

For anyone who has trouble using TargetDataLine for sound extraction in the future, the class WaveData by Ganesh Tiwari contains a very helpful method that turns bytes into a float array (http://code.google.com/p/speech-recognition-java-hidden-markov-model-vq-mfcc/source/browse/trunk/SpeechRecognitionHMM/src/org/ioe/tprsa/audio/WaveData.java):

public float[] extractFloatDataFromAudioInputStream(AudioInputStream audioInputStream) {
    format = audioInputStream.getFormat();
    audioBytes = new byte[(int) (audioInputStream.getFrameLength() * format.getFrameSize())];
    // calculate durationSec
    float milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / audioInputStream.getFormat().getFrameRate());
    durationSec = milliseconds / 1000.0;
    // System.out.println("The current signal has duration "+durationSec+" Sec");
    try {
        audioInputStream.read(audioBytes);
    } catch (IOException e) {
        System.out.println("IOException during reading audioBytes");
        e.printStackTrace();
    }
    return extractFloatDataFromAmplitudeByteArray(format, audioBytes);
}

使用此功能,我可以得到声音幅度数据。

Using this I can get sound amplitude data.

这篇关于来自TargetDataLine的声波的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 00:27