您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“C#如何實現文字轉語音功能”,內容詳細,步驟清晰,細節處理妥當,希望這篇“C#如何實現文字轉語音功能”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
效果圖
關鍵是,c#有現成的一個引用
右鍵點擊項目 > 添加引用 > .Net > 找到System.Speech點擊確定
控制臺程序代碼:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TxtToVoice { class Program { [STAThread] //默認線程模型是單線程單元 (STA) 模式 static void Main(string[] args) { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); //return; OpenFileDialog open = new OpenFileDialog(); open.Title = "請選擇文本"; //打開的文件選擇對話框上的標題 open.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";//設置文件類型 open.InitialDirectory = @"D:\project\";//默認打開目錄 open.FilterIndex = 1;//設置默認文件類型顯示順序 open.RestoreDirectory = false;//是否記憶上次打開的目錄 //open.Multiselect = true;//是否允許多選 string content=string.Empty; if (open.ShowDialog() == DialogResult.OK)//按下確定選擇的按鈕 { string[] filename = open.FileNames;//獲取多個文件的路徑及文件名并存入數組 MessageBox.Show(filename[0]); // MessageBox.Show(filename[1]); // MessageBox.Show(open.FileName); //獲取路徑及文件名 // MessageBox.Show(open.SafeFileName);//獲取文件名 content = ReadFile(filename[0]); } //-----------------------------------讀出文件內容--------------------------------- SpeechSynthesizer voice = new SpeechSynthesizer(); //創建語音實例 voice.Rate = -1; //設置語速,[-10,10] voice.Volume = 100; //設置音量,[0,100] //voice.SpeakAsync("Hellow Word"); //播放指定的字符串,這是異步朗讀 //下面的代碼為一些SpeechSynthesizer的屬性,看實際情況是否需要使用 voice.SpeakAsyncCancelAll(); //取消朗讀 voice.Speak(content); //同步朗讀 voice.Pause(); //暫停朗讀 voice.Resume(); //繼續朗讀 voice.Dispose(); //釋放所有語音資源 } /// <summary> /// 讀取文件,返回相應字符串 /// </summary> /// <param name="fileName">文件路徑</param> /// <returns>返回文件內容</returns> private static string ReadFile(string fileName) { StringBuilder str = new StringBuilder(); using (FileStream fs = File.OpenRead(fileName)) { long left = fs.Length; int maxLength = 100;//每次讀取的最大長度 int start = 0;//起始位置 int num = 0;//已讀取長度 while (left > 0) { byte[] buffer = new byte[maxLength];//緩存讀取結果 char[] cbuffer = new char[maxLength]; fs.Position = start;//讀取開始的位置 num = 0; if (left < maxLength) { num = fs.Read(buffer, 0, Convert.ToInt32(left)); } else { num = fs.Read(buffer, 0, maxLength); } if (num == 0) { break; } start += num; left -= num; str = str.Append(Encoding.UTF8.GetString(buffer)); } } return str.ToString(); } } }
窗體代碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace TxtToVoiceForm { public partial class Form2 : Form { private SpeechSynthesizer speech; /// <summary> /// 音量 /// </summary> private int value = 100; /// <summary> /// 語速 /// </summary> private int rate; public Form2() { InitializeComponent(); ReadlocalFile(); comboBox1.SelectedIndex = 0; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { rate = Int32.Parse(comboBox1.Text); } //private void 打開文件ToolStripMenuItem_Click(object sender, EventArgs e) //{ // this.ReadlocalFile(); //} /// <summary> /// 讀取本地文本文件的方法 /// </summary> private void ReadlocalFile() { var open = new OpenFileDialog(); open.ShowDialog(); //得到文件路徑 string path = open.FileName; if (path.Trim().Length == 0) { return; } var os = new StreamReader(path, Encoding.UTF8); string str = os.ReadToEnd(); textBox1.Text = str; } private void 清空內容ToolStripMenuItem_Click(object sender, EventArgs e) { textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { string text = textBox1.Text; if (text.Trim().Length == 0) { MessageBox.Show("不能閱讀空內容!", "錯誤提示"); return; } if (button1.Text == "語音試聽") { speech = new SpeechSynthesizer(); new Thread(Speak).Start(); button1.Text = "停止試聽"; } else if (button1.Text == "停止試聽") { speech.SpeakAsyncCancelAll();//停止閱讀 button1.Text = "語音試聽"; } } private void Speak() { speech.Rate = rate; //speech.SelectVoice("Microsoft Lili");//設置播音員(中文) //speech.SelectVoice("Microsoft Anna"); //英文 speech.Volume = value; speech.SpeakAsync(textBox1.Text);//語音閱讀方法 speech.SpeakCompleted += speech_SpeakCompleted;//綁定事件 } /// <summary> /// 語音閱讀完成觸發此事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void speech_SpeakCompleted(object sender, SpeakCompletedEventArgs e) { button1.Text = "語音試聽"; } /// <summary> /// 拖動進度條事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void trackBar1_Scroll(object sender, EventArgs e) { //因為trackBar1的值為(0-10)之間而音量值為(0-100)所以要乘10; value = trackBar1.Value * 10; } private void button2_Click(object sender, EventArgs e) { string text = textBox1.Text; if (text.Trim().Length == 0) { MessageBox.Show("空內容無法生成!", "錯誤提示"); return; } this.SaveFile(text); } /// <summary> /// 生成語音文件的方法 /// </summary> /// <param name="text"></param> private void SaveFile(string text) { speech = new SpeechSynthesizer(); var dialog = new SaveFileDialog(); dialog.Filter = "*.wav|*.wav|*.mp3|*.mp3"; dialog.ShowDialog(); string path = dialog.FileName; if (path.Trim().Length == 0) { return; } speech.SetOutputToWaveFile(path); speech.Volume = value; speech.Rate = rate; speech.Speak(text); speech.SetOutputToNull(); MessageBox.Show("生成成功!在" + path + "路徑中!", "提示"); } private void label1_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { this.ReadlocalFile(); } } }
讀到這里,這篇“C#如何實現文字轉語音功能”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。