如何解决错误“无法转换为com.sun.speech.freetts.VoiceDirectory”?

时间:2018-10-26 12:08:41

标签: java classcastexception freetts

我试图在我的Java程序中使用FreeTTS(来自https://freetts.sourceforge.io/docs/index.php),但出现此错误:java.lang.ClassCastException: com.sun.speech.freetts.en.us.cmu_time_awb.AlanVoiceDirectory cannot be cast to com.sun.speech.freetts.VoiceDirectory

我尝试将Free TTS jar文件重新添加到我的项目中,这是我的代码:

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class TextToSpeech {
//String voiceName = "kevin16";
VoiceManager freeVM;
Voice voice;
public TextToSpeech(String words) {
    freeVM = VoiceManager.getInstance();
    voice = VoiceManager.getInstance().getVoice("kevin16");
    if (voice != null) {
        voice.allocate();//Allocating Voice
    }

    try {
        voice.setRate(190);//Setting the rate of the voice
        voice.setPitch(150);//Setting the Pitch of the voice
        voice.setVolume(3);//Setting the volume of the voice
        SpeakText(words);// Calling speak() method


    } catch (Exception e1) {
        e1.printStackTrace();
    }



}

public void SpeakText(String words) {
    voice.speak(words);
}

我从另一个这样的类调用TextToSpeech构造函数:

 new TextToSpeech("Hello World");

不胜感激!

2 个答案:

答案 0 :(得分:1)

像这样更改TextToSpeech构造器:

public TextToSpeech(String words) {
    System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
    voice = VoiceManager.getInstance().getVoice("kevin16");
    if (voice != null) {
        voice.allocate();// Allocating Voice
        try {
            voice.setRate(190);// Setting the rate of the voice
            voice.setPitch(150);// Setting the Pitch of the voice
            voice.setVolume(3);// Setting the volume of the voice
            SpeakText(words);// Calling speak() method

        } catch (Exception e1) {
            e1.printStackTrace();
        }

    } else {
        throw new IllegalStateException("Cannot find voice: kevin16");
    }
}

该想法是指示freetts使用com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory类而不是AlanVoiceDirectory类。

答案 1 :(得分:0)

代码更改:

代替下面的行

freeVM = VoiceManager.getInstance();
voice = VoiceManager.getInstance().getVoice("kevin16");

修改为

freeVM = VoiceManager.getInstance();
voice = freeVM.getVoice("kevin16");

请参考此处给出的示例代码库:FreeTTS unable to find any voice