让Java说话-用Java实现语音引擎(二)

2014-11-23 21:35:09 · 作者: · 浏览: 21
[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()方法既可以通过上面的main()方法调用,也可以在Java程序中直接调用。从表面上看,sayPhoneWord()方法比较复杂,其实并非如此。实际上,它简单地遍历所有单词的语音元素(在输入字符串中语音元素以“|”分隔),通过一个声音输出通道一个元素一个元素地播放出来。为了让声音更自然