示例#1
0
        /// <summary>
        /// 把文本转换成声音,写入指定的内存流
        /// </summary>
        /// <param name="text">要转化成语音的文字</param>
        /// <param name="stream">合成结果输出的音频流</param>
        protected void RawAudioFromText(List <SpeechPart> output, string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }
            try
            {
                if (this.SessionId == null)
                {
                    this.SessionId = TTSInterop.SessionBegin(
                        new TtsSessionParameters(this.Speaker, this.Speed, this.Volume, this.SampleRate));
                }
                TTSInterop.TextPut(this.SessionId, text, null);
                SynthStatusEnums synth_status = SynthStatusEnums.TTS_FLAG_STILL_HAVE_DATA;

                int    lastTextOffset = 0; //上次结果对应文本偏移量
                int    lastTextLength = 0; //上次结果对应文本长度
                byte[] tmpArray       = Encoding.Unicode.GetBytes(text);
                while (synth_status == SynthStatusEnums.TTS_FLAG_STILL_HAVE_DATA)
                {
                    byte[] audioData       = TTSInterop.AudioGet(this.SessionId, ref synth_status);
                    string posStr          = TTSInterop.AudioInfo(this.SessionId);
                    int    currentPosition = int.Parse(posStr.Substring(4));
                    if (currentPosition - (lastTextOffset + lastTextLength) <= 0)
                    {//还是上次那段文本的结果
                     //保持不变
                    }
                    else
                    {//新段文本的结果
                        lastTextOffset = lastTextOffset + lastTextLength;
                        lastTextLength = currentPosition - lastTextOffset;
                    }
                    SpeechPart speechPart = new SpeechPart(
                        lastTextOffset / 2,
                        lastTextLength / 2,
                        tmpArray.Length / 2,
                        Encoding.Unicode.GetString(tmpArray, lastTextOffset, lastTextLength),
                        audioData);
                    if (ProgressChanged != null)
                    {
                        ProgressChanged(this, new ProgressChangedEventArgs(speechPart));
                    }

                    output.Add(speechPart);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return;
            }
            finally
            {
                TTSInterop.SessionEnd(this.SessionId, "normal end");
                this.SessionId = null;
            }
        }
 public ProgressChangedEventArgs(SpeechPart data)
 {
     this.Data = data;
 }