1. 程式人生 > >C#文字轉語音以及語音閱讀小例項

C#文字轉語音以及語音閱讀小例項

轉載自:猿哥愛碼
c#實現語音閱讀以及文字轉語音檔案是基於c#的一個類庫(SpeechSynthesizer )實現的,
使用該類必須要新增引用using System.Speech.Synthesis;直接是無法新增引用的,
先對專案進行新增應用

示例圖
在這裡插入圖片描述
在這裡插入圖片描述
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.Windows.Forms;
namespace 文字轉語音Demo
{
public partial class Form1 : Form
{
private SpeechSynthesizer speech;

///
/// 音量
///
private int value=100;
///
/// 語速
///
private int rate;
public Form1()
{
InitializeComponent();

comboBox1.SelectedIndex = 10;
}

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;//繫結事件
}

///
/// 語音閱讀完成觸發此事件
///
///
///
void speech_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
button1.Text = “語音試聽”;
}

///
/// 拖動進度條事件
///
///
///
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);

}

///
/// 生成語音檔案的方法
///
///
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 comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
rate = Int32.Parse(comboBox1.Text);
}

private void 開啟檔案ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.ReadlocalFile();

}

///
/// 讀取本地文字檔案的方法
///
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 = “”;
}

}
}

程式執行效果截圖
在這裡插入圖片描述