我创建了一个Web项目
public class HomeController : ApiController { public SpeechSynthesizer speechSyn = new SpeechSynthesizer(); /// <summary> /// 返回MP3路径 /// </summary> /// <param name="article">文章</param> /// <param name="name">mp3名称</param> /// <param name="isHTML">是否html</param> /// <returns></returns> [HttpPost] [Route("SpeechArticle")] public IHttpActionResult SpeechArticle(SpeechArticleViewModel model) { try { // 如果是html 则 过滤html 提取 文本 if (model.isHTML) model.article = GetStringFilterHtml(model.article); var voices = speechSyn.GetInstalledVoices().ToList(); speechSyn.SpeakAsyncCancelAll(); speechSyn.Rate = 0; //语速 speechSyn.Volume = 100; //音量 var selectedValue = voices[0]; if (selectedValue is InstalledVoice voiceInfo) { speechSyn.SelectVoice(voiceInfo.VoiceInfo.Name); }
//创建一个保存文件的文件夹 Directory.CreateDirectory("D:\articleMP3"); string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) + $"D:\articleMP3\{model.name}.mp3"; if (File.Exists(filePath)) { //File.Delete(filePath); //如果文件已经存在 直接返回文件所在路径 return Json(filePath); } else { speechSyn.SetOutputToWaveFile(filePath); speechSyn.Speak(model.article); speechSyn.SetOutputToDefaultAudioDevice(); //保存录音文件成功,保存路径:filePath return Json(filePath); } } catch (Exception ex) { throw ex; } } /// <summary> /// 字符串过滤Html标签 /// </summary> /// <param name="strHtml">待转化的字符串</param> /// <returns>经过转化的字符串</returns> public string GetStringFilterHtml(string strHtml) { try { if (String.IsNullOrEmpty(strHtml)) { return strHtml; } else { string[] aryReg ={ @"<script[^>]*?>.*?</script>", @"<!--.* (-->)?", @"<(/s*)?(.| )*?(/s*)?>", @"<(w|s|""|'| |=|\|.|/|#)*", @"([ |s])*", @"&(quot|#34);", @"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);", @"&(pound|#163);", @"&(copy|#169);", @"&#(d+);"}; string newReg = aryReg[0]; string strOutput = strHtml.Replace(" ", " "); for (int i = 0; i < aryReg.Length; i++) { Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase); strOutput = regex.Replace(strOutput, ""); } strOutput.Replace("<", ">"); strOutput.Replace(">", "<"); return strOutput.Replace(" ", " "); } } catch { return strHtml; } } }
这是后端的一个接口 发布到IIS上 可供所有网站使用 给方法提供内容 返回语音路径
大家可以先用窗体程序 或者 控制台 进行测试
下面链接是我做的Demo及前端调用接口说明
链接: https://pan.baidu.com/s/1krvRkwjWmLdcUQwM1e0PRQ 提取码: y53d
如需转载,请标注原文。