import java.net.*; public class Talker { private SourceDataLine line=null; } 如果从命令行执行Talker,下面的main()方法将作为入口点运行。main()方法获取第一个命令行参数,然后把它传递给sayPhoneWord()方法: /* * 读出在命令行中指定的表示读音的字符串 */ public static void main(String args[]) { Talker player=new Talker(); if (args.length>0) player.sayPhoneWord(args[0]); System.exit(0); } 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) {} } 现在回过头来看sayPhoneWord(),这里还有一个方法我们没有分析,即getSound()方法。 getSound()方法从一个au文件以字节数据的形式读入预先录制的声音样本。要了解读取数据、转换音频格式、初始化声音输出行(SouceDataLine)以及构造字节数据的详细过程,请参考下面代码中的注释: /* * 该方法从文件读取一个音素, * 并把它转换成byte数组 */ private byte[] getSound(String fileName) { try { URL url=Talker.class.getResource(fileName); AudioInputStream stream = AudioSystem.getAudioInputStream(url); AudioFormat format = stream.getFormat();
(编辑:aniston)
·2024年12月目录 ·2024年11月目录 ·2024年10月目录 ·2024年9月目录 ·2024年8月目录 ·2024年7月目录 ·2024年6月目录 ·2024年5月目录 ·2024年4月目录 ·2024年3月目录 ·2024年2月目录 ·2024年1月目录 ·2023年12月目录 ·2023年11月目录