1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import org.slf4j.Logger; import com.jacob.com.Variant; import com.jacob.com.Dispatch; import org.slf4j.LoggerFactory; import com.jacob.activeX.ActiveXComponent;
public class AudioFrequencyOperating {
private static final Logger log = LoggerFactory.getLogger(StringOperatingUtil.class);
public static void textToSpeech(Integer volume, Integer rate, String text, Boolean whetherGenerateFile) {
if (volume == null || !(0 < volume && volume <= 100)) throw new RuntimeException("音量输出超出范围"); if (rate == null || !(-10 <= rate && rate <= 10)) throw new RuntimeException("朗读速度超出范围");
try {
ActiveXComponent activeXComponent = new ActiveXComponent("Sapi.SpVoice"); Dispatch dispatch = activeXComponent.getObject(); activeXComponent.setProperty("Volume", new Variant(volume)); activeXComponent.setProperty("Rate", new Variant(rate)); Dispatch.call(dispatch, "Speak", new Variant(text));
log.info("音频输出成功");
if (whetherGenerateFile) { activeXComponent = new ActiveXComponent("Sapi.SpFileStream"); Dispatch spFileStream = activeXComponent.getObject();
activeXComponent = new ActiveXComponent("Sapi.SpAudioFormat"); Dispatch spAudioFormat = activeXComponent.getObject();
Dispatch.put(spAudioFormat, "Type", new Variant(22)); Dispatch.putRef(spFileStream, "Format", spAudioFormat); Dispatch.call(spFileStream, "Open", new Variant("./text.mp3"), new Variant(3), new Variant(true)); Dispatch.putRef(dispatch, "AudioOutputStream", spFileStream); Dispatch.put(dispatch, "Volume", new Variant(100)); Dispatch.put(dispatch, "Rate", new Variant(0)); Dispatch.call(dispatch, "Speak", new Variant(text)); Dispatch.call(spFileStream, "Close"); Dispatch.putRef(dispatch, "AudioOutputStream", null);
log.info("音频文件已生成到项目的根目录下");
spAudioFormat.safeRelease(); spFileStream.safeRelease();
}
dispatch.safeRelease(); activeXComponent.safeRelease();
} catch (Exception e) { throw new RuntimeException(e); } } }
|