FreeTTS - 一次发出多个声音

时间:2018-01-03 08:33:24

标签: java multithreading text-to-speech freetts

我目前正在编写一个需要文本转语音的Java应用程序(聊天应用程序)。在网上查了一下之后我发现FreeTTS是一个不错的选择,我设法让它工作,它当前阻止了主UI线程被阻止,因为我在一个线程中运行它。

唯一的问题是FreeTTS只允许一个语音同时说话(即使它们在多个线程中作为多个实例)。有没有办法可以绕过这个并拥有多个用户'马上说话?这是我到目前为止的代码。

import lombok.extern.slf4j.Slf4j;

import java.beans.PropertyVetoException;
import java.util.Locale;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;

@Slf4j
public enum Speech implements SpeechAgent {

    Instance;
    private static Random pool = new Random();

    private static Synthesizer createSynthesizer() {
        try {
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            SynthesizerModeDesc desc = new SynthesizerModeDesc(Locale.US);
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            Synthesizer synthesizer = Central.createSynthesizer(desc);
            synthesizer.allocate();
            synthesizer.resume();

            Voice[] voices = null;

            while (voices == null) {
                voices = ((SynthesizerModeDesc) synthesizer.getEngineModeDesc()).getVoices();
            }
            synthesizer.getSynthesizerProperties().setVoice(voices[pool.nextInt(voices.length)]);
            return synthesizer;

        } catch (Exception e) {
            log.error(String.format("Failed to load synthesizer: %s", e.toString()));
        }

        return null;
    }

    public void speak(String input) {
        new Thread(new Runnable() {
            public void run() {
                Synthesizer synthesizer = createSynthesizer();

                if (synthesizer == null) {
                    return;
                }

                synthesizer.speakPlainText(input.replaceAll("[^a-zA-Z ]+", ""), null);

            }
        }).start();
    }
}

线程中抛出的错误:

Trouble while processing utterance java.lang.IllegalStateException: Syllable relation has already been set
java.lang.IllegalStateException: Syllable relation has already been set
    at com.sun.speech.freetts.Segmenter.processUtterance(Segmenter.java:56)
    at com.sun.speech.freetts.Voice.runProcessor(Voice.java:595)
    at com.sun.speech.freetts.Voice.processUtterance(Voice.java:414)
    at com.sun.speech.freetts.Voice.speak(Voice.java:289)
    at com.sun.speech.freetts.jsapi.FreeTTSSynthesizer$OutputHandler.outputItem(FreeTTSSynthesizer.java:695)
    at com.sun.speech.freetts.jsapi.FreeTTSSynthesizer$OutputHandler.run(FreeTTSSynthesizer.java:622)

0 个答案:

没有答案