My capture sound method returns empty byte array tho I have mic plugged in?
Hi!
Im trying to capture audio using a mic put in the mic input on my computer.
So I modded a capture audio file that I found on the internet but for some
reason it does not work for me?
It doesnt return null, which meens it has been recordning.
Tho all spots in the byte array returned is empty (null).
Any idea how this is possible?
Heres my code:
Code:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Mixer.Info;
import javax.sound.sampled.TargetDataLine;
public class CaptureFrequency {
public static byte[] captureAudio() {
try {
Mixer.Info[] mixersInfo = AudioSystem.getMixerInfo();
//select virtual audiodevice by vendor name, device name or version
Mixer.Info selectedMixerInfo = mixersInfo[3];
TargetDataLine recordLine = AudioSystem.getTargetDataLine(getFormat(), selectedMixerInfo);
final AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
Capture obj = new Capture(format,recordLine);
return obj.getByteArray();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-2);
}
return null;
}
private static AudioFormat getFormat() {
float sampleRate = 8000.0f;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,bigEndian);
}
}
class Capture implements Runnable{
int bufferSize = 0;
byte buffer[] = new byte[bufferSize];
private byte[] array;
private TargetDataLine line;
boolean running = false;
public Capture(AudioFormat format, TargetDataLine line){
bufferSize = (int) format.getSampleRate() * format.getFrameSize();
this.line = line;
}
public byte[] getByteArray(){
new Thread(this).start();
running = true;
while(running){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return array;
}
public void run() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
running = true;
int max = 0;
try {
while (running) {
int count = line.read(buffer, 0, buffer.length);
if (count > 0) {
System.out.println("Writing");
out.write(buffer, 0, count);
}
max++;
if (max > 600000){
System.out.println("Stopping");
running = false;
}
}
array = out.toByteArray();
out.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}
}
}