TextToSpeech.java
package server.restful.common.text2speech;
import libsidplay.config.IAudioSection;
import libsidplay.config.ISidPlay2Section;
import libsidutils.AudioUtils;
import sidplay.Player;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.function.Consumer;
import static libsidutils.IOUtils.ioWrap;
@SuppressWarnings("CanBeFinal")
public class TextToSpeech implements Consumer<Player> {
private final TextToSpeechType textToSpeechType;
private final TextToSpeechBean textToSpeechBean;
public TextToSpeech(TextToSpeechType textToSpeechType, TextToSpeechBean textToSpeechBean) {
this.textToSpeechType = textToSpeechType;
this.textToSpeechBean = textToSpeechBean;
}
@Override
public void accept(Player player) {
File wavFile = null;
try {
ISidPlay2Section sidplay2Section = player.getConfig().getSidplay2Section();
IAudioSection audioSection = player.getConfig().getAudioSection();
wavFile = File.createTempFile("text2speech", ".wav", sidplay2Section.getTmpDir());
textToSpeechBean.setVolume(audioSection.getMainVolume());
/*Process textToSpeechProcess =*/
textToSpeechType.createProcess(textToSpeechBean, wavFile);
try (InputStream is = new FileInputStream(wavFile)) {
short[] samples = AudioUtils.convertToMonoWithSampleRate(is, Integer.MAX_VALUE,
audioSection.getSamplingRate());
for (short sample : samples) {
player.getAudioDriver().buffer().putShort(sample);
if (!player.getAudioDriver().buffer().putShort(sample).hasRemaining()) {
player.getAudioDriver().write();
player.getAudioDriver().buffer().clear();
}
}
}
} catch (Throwable e) {
System.err.println(
"Error during Text2Speech! Install or deactivate it!? (apt-get install espeak or sudo apt install libttspico-utils)\n"
+ e.getMessage());
} finally {
if (wavFile != null) {
ioWrap(wavFile::delete);
}
}
}
}