Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of converting text to speech in C #

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to realize the text-to-voice function in C#". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to realize the text-to-voice function in C#" can help you solve your doubts. Let's follow the editor's ideas slowly and deeply, together to learn new knowledge.

Effect picture

The point is, c # has a ready-made reference

Right-click project > add reference > .net > find System.Speech and click OK

Console program code:

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] / default threading model is single-threaded unit (STA) mode static void Main (string [] args) {/ / Application.EnableVisualStyles () / / Application.SetCompatibleTextRenderingDefault (false); / / Application.Run (new Form1 ()); / / return; OpenFileDialog open = new OpenFileDialog (); open.Title = "Please select text" / / the title open.Filter on the open file selection dialog box is open.Filter = "text files (* .txt) | * .txt | all files (*. *) | *. *"; / / set file type open.InitialDirectory = @ "D:\ project\"; / / Open directory open.FilterIndex = 1 by default / / set the default file type display order open.RestoreDirectory = false;// whether to remember the last opened directory / / open.Multiselect = true;// allows multi-selection of string content=string.Empty If (open.ShowDialog () = = DialogResult.OK) / / Press the OK selected button {string [] filename = open.FileNames;// to get the paths and file names of multiple files and store them in the array MessageBox.Show (filename [0]); / / MessageBox.Show (filename [1]) / / MessageBox.Show (open.FileName); / / get the path and file name / / MessageBox.Show (open.SafeFileName); / / get the file name content = ReadFile (filename [0]) } / /-- read the contents of the file-- SpeechSynthesizer voice = new SpeechSynthesizer () / / create a voice instance voice.Rate =-1; / / set the speech speed, [- 10Ling 10] voice.Volume = 100; / / set the volume, [0100] / / voice.SpeakAsync ("Hellow Word") / / play the specified string, which is asynchronously read / / the following code is some SpeechSynthesizer properties, depending on whether voice.SpeakAsyncCancelAll () is needed; / / cancel reading voice.Speak (content); / / synchronously read voice.Pause (); / / pause reading voice.Resume () / / continue to read voice.Dispose (); / / release all voice resources} / read the file, return the corresponding string / file path / return the file content private static string ReadFile (string fileName) {StringBuilder str = new StringBuilder () Using (FileStream fs = File.OpenRead (fileName)) {long left = fs.Length; int maxLength = 100 / maximum length of each read int start = 0 / start position int num = 0 / / read length while (left > 0) {byte [] buffer = new byte [maxLength]; / / cache read result char [] cbuffer = new char [maxLength]; fs.Position = position where start;// read starts 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 ();}

Form code:

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; / Volume / private int value = 100 / Speed / 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 Open the file ToolStripMenuItem_Click (object sender, EventArgs e) / / {/ / this.ReadlocalFile (); / /} / method to read the local text file / private void ReadlocalFile () {var open = new OpenFileDialog (); open.ShowDialog () / / get the file path 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 clears the content 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 ("cannot read empty content!", "error message"); return;} if (button1.Text = = "voice audition") {speech = new SpeechSynthesizer () New Thread (Speak) .Start (); button1.Text = "stop audition";} else if (button1.Text = = "stop audition") {speech.SpeakAsyncCancelAll (); / / stop reading button1.Text = "voice audition" }} private void Speak () {speech.Rate = rate; / / speech.SelectVoice ("Microsoft Lili"); / / set up announcer (Chinese) / / speech.SelectVoice ("Microsoft Anna"); / / English speech.Volume = value; speech.SpeakAsync (textBox1.Text) / / Voice reading method speech.SpeakCompleted + = speech_SpeakCompleted;// binding event} / void speech_SpeakCompleted (object sender, SpeakCompletedEventArgs e) {button1.Text = "voice audition" triggered by the completion of voice reading } / drag the progress bar event / private void trackBar1_Scroll (object sender, EventArgs e) {/ / because the trackBar1 value is between (0-10) and the volume value is (0-100), multiply by 10 Value = trackBar1.Value * 10;} private void button2_Click (object sender, EventArgs e) {string text = textBox1.Text; if (text.Trim (). Length = = 0) {MessageBox.Show ("empty content cannot be generated!", "error prompt"); return } this.SaveFile (text);} / 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 ("generated successfully! In the "+ path +" path! , "prompt");} private void label1_Click (object sender, EventArgs e) {} private void label3_Click (object sender, EventArgs e) {this.ReadlocalFile () After reading this, the article "how to realize the text-to-voice function of C#" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report