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

2004-02-14 09:34 出处:eNet硅谷动力 作者:仙人掌工作室 责任编辑:pjl
现在回过头来看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(); // 把一个ALAW/ULAW声音转换成PCM以便回放 if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW)) { AudioFormat tmpFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); stream = AudioSystem.getAudioInputStream(tmpFormat, stream); format = tmpFormat; } DataLine.Info info = new DataLine.Info( Clip.class, format, ((int) stream.getFrameLength() * format.getFrameSize())); if (line==null) { // 输出线还没有实例化 // 是否能够找到合适的输出线类型? DataLine.Info outInfo = new DataLine.Info(SourceDataLine.class, format); if (!AudioSystem.isLineSupported(outInfo)) { System.out.println("不支持匹配" + outInfo + "的输出线"); throw new Exception("不支持匹配" + outInfo + "的输出线"); } // 打开输出线 line = (SourceDataLine) AudioSystem.getLine(outInfo); line.open(format, 50000); line.start(); } int frameSizeInBytes = format.getFrameSize(); int bufferLengthInFrames = line.getBufferSize() / 8; int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes; byte[] data=new byte[bufferLengthInBytes]; // 读取字节数据,并计数 int numBytesRead = 0; if ((numBytesRead = stream.read(data)) != -1) { int numBytesRmaining = numBytesRead; } // 把字节数据切割成合适的大小 byte[] newData=new byte[numBytesRead]; for (int i=0; i newData[i]=data[i]; return newData; } catch (Exception e) { return new byte[0]; } } 这就是全部的代码,包括注释在内,一个大约150行代码的语音合成器。
键盘也能翻页,试试“← →”键

关注我们

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