Sound wave from TargetDataLine
Asked Answered
S

1

1

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.

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]);
}

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

Silsbye answered 26/1, 2013 at 23:8 Comment(1)
For better help sooner, post an SSCCE.Skiplane
S
0

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.

Silsbye answered 27/1, 2013 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.