private void listenSound(long songId, boolean isMatching)
throws LineUnavailableException, IOException,
UnsupportedAudioFileException {
AudioFormat formatTmp = null;
TargetDataLine lineTmp = null;
String filePath = fileTextField.getText();
AudioInputStream din = null;
AudioInputStream outDin = null;
PCM2PCMConversionProvider conversionProvider = new PCM2PCMConversionProvider();
boolean isMicrophone = false;
if (filePath == null || filePath.equals("") || isMatching) {
formatTmp = getFormat(); // Fill AudioFormat with the wanted
// settings
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
formatTmp);
lineTmp = (TargetDataLine) AudioSystem.getLine(info);
isMicrophone = true;
} else {
AudioInputStream in;
if (filePath.contains("http")) {
URL url = new URL(filePath);
in = AudioSystem.getAudioInputStream(url);
} else {
File file = new File(filePath);
in = AudioSystem.getAudioInputStream(file);
}
AudioFormat baseFormat = in.getFormat();
System.out.println(baseFormat.toString());
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
if (!conversionProvider.isConversionSupported(getFormat(),
decodedFormat)) {
System.out.println("Conversion is not supported");
}
System.out.println(decodedFormat.toString());
outDin = conversionProvider.getAudioInputStream(getFormat(), din);
formatTmp = decodedFormat;
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
formatTmp);
lineTmp = (TargetDataLine) AudioSystem.getLine(info);
}
final AudioFormat format = formatTmp;
final TargetDataLine line = lineTmp;
final boolean isMicro = isMicrophone;
final AudioInputStream outDinSound = outDin;
if (isMicro) {
try {
line.open(format);
line.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
final long sId = songId;
final boolean isMatch = isMatching;
Thread listeningThread = new Thread(new Runnable() {
public void run() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
running = true;
int n = 0;
byte[] buffer = new byte[(int) 1024];
try {
while (running) {
n++;
if (n > 1000)
break;
int count = 0;
if (isMicro) {
count = line.read(buffer, 0, 1024);
} else {
count = outDinSound.read(buffer, 0, 1024);
}
if (count > 0) {
out.write(buffer, 0, count);
}
}
byte b[] = out.toByteArray();
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
try {
makeSpectrum(out, sId, isMatch);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter outFile = new BufferedWriter(fstream);
byte bytes[] = out.toByteArray();
for (int i = 0; i < b.length; i++) {
outFile.write("" + b[i] + ";");
}
outFile.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
out.close();
line.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}