我正在尝试使用Java Audio API生成具有不同频率的两个正弦波的立体声,但我既不能使用双声道系统,也不能使用我的音调,出于某种原因,在播放时会中断和重启。 / p>
我的源代码:
public class GeradorSinal extends javax.swing.JFrame {
int fs = 48000;
AudioFormat af = new AudioFormat(fs, 8, 1, true, true);
SourceDataLine line;
Thread generator;
boolean parar = false;
byte[] senoid = new byte[1];
/**
* Creates new form GeradorSinal
*/
public GeradorSinal() {
initComponents();
try {
line = AudioSystem.getSourceDataLine(af);
line.open(af, fs);
} catch (LineUnavailableException e) {
System.err.println(e.getMessage());
}
}
public static double scale(
double x,
double old_min, double old_max,
double new_min, double new_max) {
double old_range = old_max - old_min;
double new_range = new_max - new_min;
return new_min + (x - old_min) * new_range / old_range;
}
private void bt_gerarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
generator = new Thread(new Runnable() {
@Override
public void run() {
long t = 0;
long f = Long.parseLong(ln_freq.getText());
line.start();
while (!parar) {
senoid[0] = (byte) scale(Math.sin(2 * Math.PI * f * t++ / fs),
-1.0, 1.0, Byte.MIN_VALUE, Byte.MAX_VALUE);
line.write(senoid, 0, 1);
}
line.stop();
}
});
generator.start();
}
private void bt_pararActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:;
parar = true;
try {
generator.join();
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
parar = false;
}
private void bt_salvarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
FileWriter fstream = new FileWriter("testes.txt", true);
try (BufferedWriter fbw = new BufferedWriter(fstream)) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
fbw.write(dateFormat.format(date));
fbw.write("\t");
fbw.write(ln_freq.getText());
fbw.write("\t");
fbw.write(String.valueOf(1.2 * Double.parseDouble(ln_freq.getText())));
fbw.write("\t");
fbw.write(ln_volume.getText());
fbw.newLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}