Hallo,
ich versuche über zwei Buttons eine Aufnahme über ein Mikrofon zu erhalten.
Der Start funktioniert, es nimmt auch auf, aber wie kann ich den Thread wieder anhalten bzw. stoppen?
ich versuche über zwei Buttons eine Aufnahme über ein Mikrofon zu erhalten.
Der Start funktioniert, es nimmt auch auf, aber wie kann ich den Thread wieder anhalten bzw. stoppen?
Java:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.sound.sampled.*;
import javax.swing.*;
public class Test1 {
private static boolean runThread = true;
private static Thread myThread;
public static void main(String[] args) {
final Test1 t1 = new Test1();
JFrame frame = new JFrame("test");
frame.setLayout(new GridLayout());
JButton button = new JButton("start");
JButton btStop = new JButton("stop");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
myThread = t1.new MyThread();
myThread.start();
runThread = true;
}
});
btStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runThread = false;
}
});
frame.getContentPane().add(button);
frame.getContentPane().add(btStop);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class MyThread extends Thread{
File wavFile = new File("d:/test.wav");
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
TargetDataLine line;
AudioFormat getAudioFormat() {
float sampleRate =16000;
int sampleSizeInBits = 8;
int channels = 2;
boolean signed = true;
boolean bigEndian = true;
AudioFormat af = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
return af;
}
public void start1() {
try {
AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// checks if system supports the data line
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start(); // start capturing
System.out.println("Start capturing...");
AudioInputStream ais = new AudioInputStream(line);
System.out.println("Start recording...");
// start recording
AudioSystem.write(ais, fileType, wavFile);
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void finish() {
line.stop();
line.close();
System.out.println("Finished");
}
@Override
public void run() {
while(runThread) {
System.out.println("Still running");
try {
((MyThread) myThread).start1();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("stop");
((MyThread) myThread).finish();
}
}
}
Zuletzt bearbeitet: