C#文字轉換語音朗讀或保存MP3、WAV等格式


最近遇到一個需求,需要把文字轉換語音,參考很多大佬寫的方法,最后經過自己改造實現文字在線朗讀、保存MP3、WAV等格式。

//需要引用System.Speech程序集
//引用using System.Speech.Synthesis;

在線朗讀代碼:

/// <summary>
/// 文字在線音頻朗讀
/// </summary>
/// <param name="readText">朗讀文本</param>
/// <returns></returns>
public static bool TextRead(string readText)
{
  var flag = false;

  if (!string.IsNullOrWhiteSpace(readText))
  {
    using (SpeechSynthesizer reader = new SpeechSynthesizer())
    {
      reader.SpeakAsync(readText);
      reader.Dispose();
      flag = true;
    }

    return flag;
  }
  else
  {
    return flag;
  }
}

保存MP3、WAV等格式:

/// <summary>
/// 文字轉換mp3格式音頻
/// </summary>
/// <param name="path">保存路徑</param>
/// <param name="input">輸入文本</param>
/// <returns></returns>
public static bool TextVonvertToMP3(string path,string input)
{
  input = input.Trim();
  if (!string.IsNullOrWhiteSpace(input))
  {
    using (SpeechSynthesizer reader = new SpeechSynthesizer())
    {

      reader.SetOutputToWaveFile(path+ input + ".mp3");
      reader.Speak(input);
      reader.SetOutputToDefaultAudioDevice();
      reader.Dispose();
    }
    return true;
  }
  return false;
}

注:忘記了參考文章出處,請各位大佬見諒!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM