文字轉(zhuǎn)語音
這個比較簡單只要引用COM中的 Microsoft Speech objcet Library
using SpeechLib;
public ActionResult speak(string speechSounds)
{
SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
SpVoice spVoice = new SpVoice();
spVoice.Rate = spVoice.Rate - 5;
if (spVoice.Volume < 100)
{
spVoice.Volume = spVoice.Volume + 10;
}
if (spVoice.Volume > 9)
{
spVoice.Volume = spVoice.Volume - 10;
}
spVoice.Speak(speechSounds, SpFlags);
return Content("成功");
}
文字生成語音文件
引用程序集中的 System.Speech
using System.Speech.Synthesis;
private SpeechSynthesizer synth = null;
/// <summary>
/// 返回一個SpeechSynthesizer對象
/// </summary>
/// <returns></returns>
private SpeechSynthesizer GetSpeechSynthesizerInstance()
{
if (synth == null)
{
synth = new SpeechSynthesizer();
}
return synth;
}
/// <summary>
/// 播放
/// </summary>
public void Play(string text)
{
Thread thread = new Thread(new ParameterizedThreadStart(SaveMp3));
thread.Start(text);
}
/// <summary>
/// 保存語音文件
/// </summary>
/// <param name="text"></param>
public void SaveMp3(object text)
{
synth = GetSpeechSynthesizerInstance();
string spText = text.ToString();
synth.Rate = 1;
synth.Volume = 100;
string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
string str = "C:\\Users\\admin1\\Desktop\\新建文件夾\\" + filename + ".wav";
synth.SetOutputToWaveFile(str);
synth.Speak(spText);
synth.SetOutputToNull();
//調(diào)用語音轉(zhuǎn)文字
//Thread threadVoice = new Thread(VoiceToText);
//threadVoice.Start(str);
}
語音轉(zhuǎn)文本

using System.Speech.Recognition;
private SpeechRecognitionEngine SRE = new SpeechRecognitionEngine();
/// <summary>
// 語音轉(zhuǎn)文本
/// </summary>
/// <param name="str"></param>
private void VoiceToText(object str)
{
try
{
string filepath = str.ToString(); ;
SRE.SetInputToWaveFile(filepath); //<=======默認(rèn)的語音輸入設(shè)備,你可以設(shè)定為去識別一個WAV文件。
GrammarBuilder GB = new GrammarBuilder();
//需要判斷的文本(相當(dāng)于語音庫)
GB.Append(new Choices(new string[] { "時間", "電話", "短信", "定位", "天氣", "幫助" }));
Grammar G = new Grammar(GB);
G.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(G_SpeechRecognized);
SRE.LoadGrammar(G);
SRE.RecognizeAsync(RecognizeMode.Multiple); //<=======異步調(diào)用識別引擎,允許多次識別(否則程序只響應(yīng)你的一句話)
}
catch (Exception ex)
{
string s = ex.ToString();
}
}
/// <summary>
/// 判斷語音并轉(zhuǎn)化為需要輸出的文本
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void G_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string result = e.Result.Text;
string RetSpeck = string.Empty;
switch (result)
{
case "時間":
RetSpeck = "你輸入了時間";
break;
case "電話":
RetSpeck = "你輸入了電話";
break;
case "短信":
RetSpeck = "你輸入了短信";
break;
case "定位":
RetSpeck = "你輸入了定位";
break;
case "天氣":
RetSpeck = "你輸入了天氣";
break;
case "幫助":
RetSpeck = "你輸入了幫助";
break;
}
speak(RetSpeck);
}
轉(zhuǎn)自:https://www.cnblogs.com/-maomao/p/6861447.html
|