如何通过 C# 将文本变为声音 ?

咨询区

  • user2110292

我的项目有一个需求需要将可以将 文本 转化为 声音,请问大家是否有开源的 C# 库 来解决这件事情?

回答区

  • HABJAN

最近 Google 发布了一个开源的 Google Cloud Text To Speech 包,.NET版本的github链接:https://github.com/jhabjan/Google.Cloud.TextToSpeech.V1

可参考下面的例子:

GoogleCredential credentials =
    GoogleCredential.FromFile(Path.Combine(Program.AppPath, "jhabjan-test-47a56894d458.json"));

TextToSpeechClient client = TextToSpeechClient.Create(credentials);

SynthesizeSpeechResponse response = client.SynthesizeSpeech(
    new SynthesisInput()
    {
        Text = "Google Cloud Text-to-Speech enables developers to synthesize natural-sounding speech with 32 voices"
    },
    new VoiceSelectionParams()
    {
        LanguageCode = "en-US",
        Name = "en-US-Wavenet-C"
    },
    new AudioConfig()
    {
        AudioEncoding = AudioEncoding.Mp3
    }
);

string speechFile = Path.Combine(Directory.GetCurrentDirectory(), "sample.mp3");

File.WriteAllBytes(speechFile, response.AudioContent);
  • HABJAN

完全不需要使用任何开源框架,在 .NET 内部提供的 System.Speech.Synthesis 类就可以帮你解决这个问题,引用下 System.speech.dll 命名空间即可。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis; // first import this package

    namespace textToSpeech
    {
        public partial class home : Form
        {
            public string s = "pran"; // storing string (pran) to s

            private void home_Load(object sender, EventArgs e)
                {
                    speech(s); // calling the function with a string argument
                }

            private void speech(string args) // defining the function which will accept a string parameter
                {
                    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                    synthesizer.SelectVoiceByHints(VoiceGender.Male , VoiceAge.Adult); // to change VoiceGender and VoiceAge check out those links below
                    synthesizer.Volume = 100;  // (0 - 100)
                    synthesizer.Rate = 0;     // (-10 - 10)
                    // Synchronous
                    synthesizer.Speak("Now I'm speaking, no other function'll work");
                    // Asynchronous
                    synthesizer.SpeakAsync("Welcome" + args); // here args = pran
                }       
         }
    }

这里简单提一下,最好用异步方式 SpeakAsync 替代同步的 Speak 方法,这样的话,调用线程就不会被阻塞,提高程序的吞吐率。

点评区

这个功能好,不过建议大家了解下强大的 Google.Cloud.TextToSpeech。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值