正在阅读:让Java说话-用Java实现语音引擎让Java说话-用Java实现语音引擎

2004-02-14 09:34 出处:eNet硅谷动力 作者:仙人掌工作室 责任编辑:pjl
sayPhoneWord()方法既可以通过上面的main()方法调用,也可以在Java程序中直接调用。从表面上看,sayPhoneWord()方法比较复杂,其实并非如此。实际上,它简单地遍历所有单词的语音元素(在输入字符串中语音元素以“|”分隔),通过一个声音输出通道一个元素一个元素地播放出来。为了让声音更自然一些,我把每一个声音样本的结尾和下一个声音样本的开头合并了起来: /* * 读出指定的语音字符串 */ public void sayPhoneWord(String word) { // 为上一个声音构造的模拟byte数组 byte[] previousSound=null; // 把输入字符串分割成单独的音素 StringTokenizer st=new StringTokenizer(word,"|",false); while (st.hasMoreTokens()) { // 为音素构造相应的文件名字 String thisPhoneFile=st.nextToken(); thisPhoneFile="/allophones/"+thisPhoneFile+".au"; // 从声音文件读取数据 byte[] thisSound=getSound(thisPhoneFile); if (previousSound!=null) { // 如果可能的话,把前一个音素和当前音素合并 int mergeCount=0; if (previousSound.length>=500 && thisSound.length>=500) mergeCount=500; for (int i=0; i { previousSound[previousSound.length-mergeCount+i] =(byte)((previousSound[previousSound.length -mergeCount+i]+thisSound[i])/2); } // 播放前一个音素 playSound(previousSound); // 把经过截短的当前音素作为前一个音素 byte[] newSound=new byte[thisSound.length-mergeCount]; for (int ii=0; ii newSound[ii]=thisSound[ii+mergeCount]; previousSound=newSound; } else previousSound=thisSound; } // 播放最后一个音素,清理声音通道 playSound(previousSound); drain(); } 在sayPhoneWord()的后面,你可以看到它调用playSound()输出单个声音样本(即一个音素),然后调用drain()清理声音通道。下面是playSound()的代码: /* * 该方法播放一个声音样本 */ private void playSound(byte[] data) { if (data.length>0) line.write(data, 0, data.length); } 下面是drain()的代码: /* * 该方法清理声音通道 */ private void drain() { if (line!=null) line.drain(); try {Thread.sleep(100);} catch (Exception e) {} }
键盘也能翻页,试试“← →”键

关注我们

最新资讯离线随时看 聊天吐槽赢奖品