C# 微软Speech文字转语音TTS

发布时间 2023-08-18 17:23:36作者: 海乐学习

.net 4.0 以上

第一步 引用 System.Speech

代码如下

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using SpeechLib;

一、直接朗读

public bool Speak(string strSpeakText,int intRate,int intVolume)
{
  try
  {
    SpeechVoiceSpeakFlags flag = SpeechVoiceSpeakFlags.SVSFlagsAsync;
    SpVoice voice = new SpVoice();
    voice.Rate = intRate;//-2;//语速
    voice.Volume = intVolume;// 100;//音量
    voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);//Item(0)中文、Item(3)英文
    //voice.Speak("这里是您要播报的语音内容,今天天气晴转多云", flag);

    voice.Speak(strSpeakText, flag);

    return true;
  }
  catch (Exception ex)
  {
    return false;
  }
}

调用方法

this.txtSpeakText.Text="您的欠费金额为2984.34元";

this.Speak(this.txtSpeakText.Text, -2, 100);

 

二、直接保存至语音文件

public bool SpeakSaveWav(string strSpeakText,string strWavFilePath)
{
try
{
SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
SpVoice Voice = new SpVoice();

//string strFileName = "TTS/" + strSpeakText + ".wav";//工程目录下以播放的内容为文件名
string strFileName = strWavFilePath;//工程目录下以播放的内容为文件名

SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;

SpFileStream SpFileStream = new SpFileStream();

SpFileStream.Format.Type = SpeechAudioFormatType.SAFT8kHz16BitMono; //8KHZ 16比特 语音格式
//SpFileStream.Format.Type = SpeechAudioFormatType.SAFT11kHz16BitMono;
//SpFileStream.Open("c:\\tts.wav", SpeechStreamFileMode.SSFMCreateForWrite, false);

SpFileStream.Open(strFileName, SpFileMode, false);

Voice.AudioOutputStream = SpFileStream;
Voice.Speak(strSpeakText, SpFlags);
Voice.WaitUntilDone(Timeout.Infinite);//Timeout.Infinite 线程超时常量

SpFileStream.Close();//关闭


log.Debug("MicrosoftTTS生成成功! " + strSpeakText + " " + strWavFilePath);

if (this.SpeakSaveSuccessEvent != null)
this.SpeakSaveSuccessEvent(strSpeakText, strWavFilePath);

return true;
}
catch (Exception ex)
{
log.Debug("MicrosoftTTS生成失败! " + strSpeakText + " " + strWavFilePath + " " + ex.Message);
if (this.SpeakSaveErrorEvent != null)
this.SpeakSaveErrorEvent(strSpeakText, strWavFilePath,ex.Message);
return false;
}
}

调用方法

this.txtSpeakText.Text="您的欠费金额为2984.34元";

strFilePath="TTS/";

string strFileName = strFilePath + txtSpeakText.Text + ".pcm";//工程目录TTS下以播放的内容为文件名

this.SpeakSaveWav(this.txtSpeakText.Text, strFileName); //存wav