I cannot figure out how to stop a Thread
in Java
.
I have a function
that creates the Thread
and starts it. Now when I start the program, I want it to start the Thread
. After that if the button
is pressed then I want the Thread
to stop and when the button
is pressed again, I want the Thread
to start over, or resume (it does not matter).
My function
that creates the Thread
:
private void startRecordingUserInput() {
AudioDispatcher dispatcher =
AudioDispatcherFactory.fromDefaultMicrophone(44100, 2048, 0);
PitchDetectionHandler pdh = new PitchDetectionHandler() {
@Override
public void handlePitch(PitchDetectionResult res, AudioEvent e) {
final float pitchInHz = res.getPitch();
runOnUiThread(new Runnable() {
@Override
public void run() {
pitchText.setText("" + pitchInHz);
gameView.setSingerArrowPitch(pitchInHz);
gameView.setCurrentTime(mid);
gameView.invalidate();
}
});
}
};
AudioProcessor pitchProcessor = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 44100, 2048, pdh);
dispatcher.addAudioProcessor(pitchProcessor);
Thread audioThread = new Thread(dispatcher, "Audio Thread");
audioThread.start();
}
And the part where I start it and want to start/stop
the Thread
.
//Start the Thread
startRecordingUserInput();
playRecordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!isPlaying){
//Start the Thread again if it is not running or
//make a new one
isPlaying = true;
} else if(isPlaying){
//Stop the Thread
isPlaying = false;
}
}
});