我试图在使用按钮的ActionEvent调用TALK(字符串文本,布尔语音录音(方法时,将文本进行到语音线程停止。
按下这些按钮时,不同的文本字符串将传递给该方法,该方法在新线程上运行音频。如果当前线程仍在运行,但发生了新的动作,我需要当前线程停止(即文本到语音(,以便可以在没有当前音频剪辑和新的剪辑播放的情况下播放新的文本到语音音频在彼此的顶部。
这是我目前拥有的,但是TTS音频互相播放。我需要当前的TT在触发新的TTS之后立即停止。我相信我的主要问题是每次称为方法时都会制作一个新线程。
任何帮助都非常感谢。谢谢!
public void talk(String text, boolean voiceEnabled) {
System.out.println(text);
// Create a new Thread as JLayer is running on the current Thread and will
// make the application lag
Thread thread = new Thread(() -> {
try {
// Create a JLayer instance
AdvancedPlayer player = new AdvancedPlayer(synthesizer.getMP3Data(text));
if (voiceEnabled) {
player.play(); //Plays the TTS audio
System.out.println("Successfully retrieved synthesizer data");
}
else {
}
} catch (IOException | JavaLayerException e) {
e.printStackTrace();
}
});
// We don't want the application to terminate before this Thread terminates
thread.setDaemon(false);
// Start the Thread
thread.start();
}
您似乎正在埋葬匿名内部类中的密钥参考,我看不出如何在需要时和在需要时找到它们。为什么这样做?为什么不创建一个非匿名类的实例,一个带有高级游戏字段的实例,其中一个字段由某些集合持有,也许是 List<...>
或hashmap,或者是一个变量,如果只有一个到两个正在运行,则可以在此处提取。该对象,获取其高级游戏字段并在其上调用.stop()
?
,例如,
public class RunnablePlayer implements Runnable {
private AdvancedPlayer player;
private String text;
private boolean voiceEnabled;
public RunnablePlayer(String text, boolean voiceEnabled) {
this.text = text;
this.voiceEnabled = voiceEnabled;
}
@Override
public void run() {
try {
// Create a JLayer instance
player = new AdvancedPlayer(synthesizer.getMP3Data(text));
if (voiceEnabled) {
player.play(); //Plays the TTS audio
System.out.println("Successfully retrieved synthesizer data");
}
} catch (IOException | JavaLayerException e) {
e.printStackTrace();
}
}
public AdvancedPlayer getPlayer() {
return player;
}
public void stop() {
// perhaps do a null check here first?
if (player != null) {
player.stop();
}
}
}
然后您可以拥有一个班级的领域,例如:
// field of the class
private RunnablePlayer runnablePlayer;
并在您的谈话方法中使用它:
public void talk(String text, boolean voiceEnabled) {
if (runnablePlayer != null) {
runnablePlayer.stop(); // not calling this on a Thread
}
runnablePlayer = new RunnablePlayer(text, voiceEnabled);
Thread thread = new Thread(runnablePlayer);
//.....
thread.start();
}
代码未编译或测试,而是提出只是为了给出一个一般的想法。