public TTS(string config) { int ret = TTS.MSPLogin("", "", config); if (ret != 0) { throw new Exception("初始化TTS引擎错误,错误代码:" + ret); } }
private void Form1_Load(object sender, EventArgs e) { statusTxtBox.Text = ""; this.appendMsg("程序启动"); _folderPath = ""; string config = "appid = 54058c94"; try { if (_tts == null) { _tts = new TTS(config); _tts.tts_SpeakFinishedEvent += new TTS.TTS_SpeakFinished(this.speakFinished); } } catch (Exception ex) { this.appendMsg(ex.Message); } }
public void end() { TTS.MSPLogout(); }
/// <summary> /// 把文字转化为声音,单路配置,一种语音 /// </summary> /// <param name="speekText">要转化成语音的文字</param> /// <param name="outWaveFlie">把声音转为文件,默认为不生产wave文件</param> private void speek(string speekText, string outWaveFlie = null) { string szParams = "ssm=0,ent=intp65_en,vcn=" + _speaker + ",aue=speex-wb;7,auf=audio/L16;rate=16000"; int ret = 0; try { sessionID = Ptr2Str(TTS.QTTSSessionBegin(szParams, ref ret)); if (ret != 0) { throw new Exception("初始化TTS引会话错误,错误代码:" + ret); } ret = TTS.QTTSTextPut(sessionID, speekText, (uint)Encoding.Default.GetByteCount(speekText), string.Empty); if (ret != 0) { throw new Exception("向服务器发送数据,错误代码:" + ret); } IntPtr audio_data; int audio_len = 0; SynthStatus synth_status = SynthStatus.MSP_TTS_FLAG_STILL_HAVE_DATA; MemoryStream ms = new MemoryStream(); ms.Write(new byte[44], 0, 44); //写44字节的空文件头 while (synth_status == SynthStatus.MSP_TTS_FLAG_STILL_HAVE_DATA) { audio_data = TTS.QTTSAudioGet(sessionID, ref audio_len, ref synth_status, ref ret); //System.Diagnostics.Debug.WriteLine("audio_len:"+audio_len); if (audio_data != IntPtr.Zero) { //System.Diagnostics.Debug.WriteLine(">0"); byte[] data = new byte[audio_len]; Marshal.Copy(audio_data, data, 0, audio_len); //System.Diagnostics.Debug.WriteLine("data.length:"+data.Length); ms.Write(data, 0, data.Length); //System.Diagnostics.Debug.WriteLine("write end"); if (synth_status == SynthStatus.MSP_TTS_FLAG_DATA_END || ret != 0) { //System.Diagnostics.Debug.WriteLine("break"); break; } } } System.Diagnostics.Debug.WriteLine("wav header"); WAVE_Header header = getWave_Header((int)ms.Length - 44); //创建wav文件头 byte[] headerByte = StructToBytes(header); //把文件头结构转化为字节数组 //写入文件头 ms.Position = 0; //定位到文件头 ms.Write(headerByte, 0, headerByte.Length); //写入文件头 /* * System.Diagnostics.Debug.WriteLine("play"); * ms.Position = 0; * System.Media.SoundPlayer pl = new System.Media.SoundPlayer(ms); * pl.Stop(); * pl.Play(); */ if (outWaveFlie != null) { //System.Diagnostics.Debug.WriteLine("outWaveFile:"+outWaveFlie); FileStream fs = new FileStream(outWaveFlie, FileMode.Create); ms.WriteTo(fs); ms.Close(); fs.Close(); ms = null; fs = null; } } catch (Exception ex) { throw new Exception("Error:" + ex.Message); } finally { ret = TTS.QTTSSessionEnd(sessionID, ""); if (ret != 0) { throw new Exception("结束TTS会话错误,错误代码:" + ret); } } }