package tw.feisty.server.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.audio.SingleFileAudioPlayer;
public class TextToSpeech {
public static void convertTextToSpeech(Voice voice, String message) {
boolean status = true;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSS");
String dateString = sdf.format(date);
//System.out.println(dateString);
//text為傳入的字串
String text = new String(message);
System.setProperty("com.sun.speech.freetts.voice.defaultAudioPlayer", "com.sun.speech.freetts.audio.SingleFileAudioPlayer");
byte[] fbytes = text.getBytes();
if(fbytes == null) {
System.out.println("no bytes");
//直接中斷程式
System.exit(1);
}
SingleFileAudioPlayer audioFile;
try {
//文字發聲起動
voice.speak(message);
audioFile = (SingleFileAudioPlayer) voice.getDefaultAudioPlayer();
System.out.println("產生" + text + "的發音檔");
audioFile.write(fbytes);
}
catch(Exception e) {
System.out.println(text + "轉檔失敗");
e.printStackTrace();
status = false;
}
voice.deallocate();
if(status == true) {
try {
System.out.println("檔案複製開始");
String copyCommand = "copy .\\freetts.wav .\\wave\\" + dateString + ".wav";
Runtime.getRuntime().exec("cmd.exe /c" + copyCommand);
System.out.println("檔案複製完成");
}
catch(Exception e) {
e.printStackTrace();
status = false;
}
}
System.out.println("status: " + status);
}
public static void main(String[] argv) {
String message = "i get up at six o'clock. i rub my eyes. i stretch out.";
VoiceManager vm = VoiceManager.getInstance();
Voice voice = vm.getVoice("kevin16");
if(voice != null) {
voice.allocate();
convertTextToSpeech(voice, message);
}
else {
//無法取得發聲引擎
System.out.println("voice is null");
}
}
}
沒有留言:
張貼留言