本文将使用C#实现一个简单的winfrom窗体应用程序,可以自定义文本转换为声音进行播放,生成音频文件。采用Microsoft提供的SpeechSynthesizer类来实现这个功能。
首先需要在代码中引用System.Speech.Synthesis命名空间,就可以使用SpeechSynthesizer类。
using System.Speech.Synthesis;
一、播放文本
public void play(string text)
{
try
{
System.Threading.Thread.Sleep(500);
WriteLogs("文本:" + text);
if (text == "")
{
MessageBox.Show("请输入音频文本");
return;
}
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
pb.AppendText(text);
synth.Speak(pb);
MessageBox.Show("播放成功");
}
catch (Exception e)
{
WriteLogs("播放失败:" + e.Message);
MessageBox.Show("播放失败:" + e.Message);
}
}
二、播放路径
public void playFile(string filename)
{
try
{
System.Threading.Thread.Sleep(500);
if (filename == "")
{
MessageBox.Show("请输入音频路径");
return;
}
SoundPlayer player = new SoundPlayer();
player.SoundLocation = filename;
player.Load();//加载
player.Play();//播放
MessageBox.Show("播放成功");
}
catch (Exception e)
{
MessageBox.Show("播放失败:" + e.Message);
}
}
三、生成音频
public void save(string text, string filename)
{
try
{
System.Threading.Thread.Sleep(500);
if (text == "")
{
MessageBox.Show("请输入音频文本");
return;
}
else if (filename == "")
{
MessageBox.Show("请输入音频路径");
return;
}
string file = filename.Substring(0, filename.LastIndexOf('/'));
bool flag= !Directory.Exists(file);
if (flag)
{
Directory.CreateDirectory(file);
}
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
pb.AppendText(text);
synth.GetInstalledVoices().ToList().ForEach(voice => Console.WriteLine(voice.VoiceInfo.Name));
synth.SelectVoice("Microsoft Huihui Desktop");
// 设置合成音频的格式
synth.SetOutputToWaveFile(filename, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
synth.Speak(pb);
MessageBox.Show("生成成功");
}
catch (Exception e)
{
MessageBox.Show("生成失败:" + e.Message);
}
}
百度网盘下载程序源码。
程序源码下载链接
提取码:pakw