csharp:Google TTS API text to speech

简介: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; usin
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using NAudio.Wave;//http://naudio.codeplex.com/
using NAudio.CoreAudioApi;
using System.Web;
using System.Media;
using SpeechLib;//NET2.0 引用 Speech sdk 5.1 在COM选项卡里面的Microsoft Speech  object  library引用 已经有11.0版本
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;


namespace Speech
{
    /// <summary>
    /// Csharp: Google TTS API 文本语音读取
    ///  涂聚文
    /// </summary>
    public partial class Form2 : Form
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FileName"></param>
        public void PlaySound(string FileName)
        {
            //要加载COM组件:Microsoft speech object Library
            if (!System.IO.File.Exists(FileName))
            {
                return;
            }

            SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
            SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
            spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
            SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
            pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
            spFs.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        public Form2()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form2_Load(object sender, EventArgs e)
        {
            this.textBox1.Text = "中华人民共和国";
            //ok
            WebClient web = new WebClient();
            web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows;)");

            string encstr = string.Empty;

            string filename = "tts.mp3"; //could also be tts.wav

            string s = "中华人民共和国涂聚文投诉";

            encstr = Uri.EscapeDataString(s);

            Console.WriteLine(encstr);

            web.DownloadFile("http://translate.google.com/translate_tts?ie=UTF-8&tl=zh-cn&q=" + encstr, ".\\" + filename);

            //PlaySound(Application.StartupPath+"\\"+filename);
            //SoundPlayer sp = new SoundPlayer();
            //sp.SoundLocation = Application.StartupPath + "\\" + filename;
            //sp.LoadAsync();
            //sp.PlaySync();
            //sp.PlayLooping();
            //Device dv = new Device();
            //SecondaryBuffer buf = new SecondaryBuffer(Application.StartupPath + "\\" + filename, dv);
            //buf.Play(0, BufferPlayFlags.Looping);
            this.axWindowsMediaPlayer1.URL = Application.StartupPath + "\\" + filename;
        }
        bool waiting = false;
        AutoResetEvent stop = new AutoResetEvent(false);
        /// <summary>
        /// 英文可以,中文不行
        /// </summary>
        /// <param name="url"></param>
        public void PlayMp3FromUrl(string url)
        {
            try
            {
                url = HttpUtility.UrlDecode(url);
                using (Stream ms = new MemoryStream())
                {
                    using (Stream stream = WebRequest.Create(url).GetResponse().GetResponseStream())//HttpUtility.UrlDecode(
                    {
                        //UTF8Encoding encoding = new UTF8Encoding();
                        //byte[] buffer = encoding.GetBytes(url);
                        //stream.Write(buffer, 0, buffer.Length);
                        //stream.Close();


                        byte[] buffer = new byte[32768];//32768
                        int read;
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        //using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                        //{
                        //    writer.Write(url);
                        //}

                    }
                    //using (Stream stream = request.GetRequestStream())
                    //using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
                    //{
                    //    writer.Write(url);
                    //}
                    ms.Position = 0;
                    using (WaveStream blockAlignedStream =
                        new BlockAlignReductionStream(
                            WaveFormatConversionStream.CreatePcmStream(
                                new Mp3FileReader(ms))))
                    {
                        using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                        {
                            waveOut.Init(blockAlignedStream);
                            waveOut.PlaybackStopped += (sender, e) =>
                            {
                                waveOut.Stop();
                            };

                            waveOut.Play();
                            waiting = true;
                            stop.WaitOne(10000);
                            waiting = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        /// <summary>
        /// http://translate.google.com/translate_tts?tl=zh-cn&q=%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD
        /// http://translate.google.cn/translate_tts?ie=UTF-8&q=%E4%B8%AD%E5%9B%BD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD&tl=zh-cn&prev=input
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            
            
            //var playThread = new Thread(() => PlayMp3FromUrl("http://translate.google.com/translate_tts?tl=en&q=" + HttpUtility.UrlEncode(this.textBox1.Text)));
            string str = HttpUtility.UrlEncode(this.textBox1.Text);
            var playThread = new Thread(() => PlayMp3FromUrl("http://translate.google.com/translate_tts?ie=UTF-8&tl=zh-cn&q=" + str));// HttpUtility.UrlEncode(
            playThread.IsBackground = true;
            playThread.Start();
        }
    }
}

目录
相关文章
|
1月前
|
人工智能 Java API
Google Gemini API 接口调用方法
Google 最近发布的 Gemini 1.0 AI 模型通过其升级版,Gemini,标志着公司迄今为止最为强大和多功能的人工智能技术的突破。
|
2月前
|
JSON 搜索推荐 API
【2024更新】如何使用google index api来自动提交url
本文提供了一个详细的指南,说明如何创建并使用使用google index api,google自动提交url来优化seo。
37 0
|
6月前
|
关系型数据库 MySQL API
Go语言微服务框架 - 6.用Google风格的API接口打通MySQL操作
随着RPC与MySQL的打通,整个框架已经开始打通了数据的出入口。 接下来,我们就尝试着实现通过RPC请求操作MySQL数据库,打通整个链路,真正地让这个平台实现可用。
18 0
|
11月前
|
Web App开发 前端开发 JavaScript
《智能前端技术与实践》——第 2 章 前端开发基础 ——2.5 与 Google 扩展程序相关的 JavaScript API
《智能前端技术与实践》——第 2 章 前端开发基础 ——2.5 与 Google 扩展程序相关的 JavaScript API
|
机器学习/深度学习 数据采集 人工智能
好饭不怕晚,Google基于人工智能AI大语言对话模型Bard测试和API调用(Python3.10)
谷歌(Google)作为开源过著名深度学习框架Tensorflow的超级大厂,是人工智能领域一股不可忽视的中坚力量,旗下新产品Bard已经公布测试了一段时间,毁誉参半,很多人把Google的Bard和OpenAI的ChatGPT进行对比,Google Bard在ChatGPT面前似乎有些技不如人。 事实上,Google Bard并非对标ChatGPT的产品,Bard是基于LaMDA模型对话而进行构建的,Bard旨在构建一个对话式的AI系统,使其能够更好地理解人类语言,并且具备进行多轮对话的能力。而GPT的目标是生成自然语言文本。
好饭不怕晚,Google基于人工智能AI大语言对话模型Bard测试和API调用(Python3.10)
|
Ubuntu JavaScript 前端开发
Google Map api国内正常使用该如何配置(2021最新)
Google Map api国内正常使用该如何配置(2021最新)
353 0
Google Map api国内正常使用该如何配置(2021最新)
EMQ
|
消息中间件 运维 Kubernetes
EMQX Enterprise 4.4.11 发布:CRL/OCSP Stapling、Google Cloud Pub/Sub 集成、预定义 API 密钥
EMQX Enterprise最新的4.4.11版本发布了CRL(证书吊销列表)与OCSP Stapling为客户端提供更灵活的安全防护,新增Google Cloud Pub/Sub集成帮助用户通过Google Cloud各类服务发掘更多物联网数据价值。
EMQ
125 0
EMQX Enterprise 4.4.11 发布:CRL/OCSP Stapling、Google Cloud Pub/Sub 集成、预定义 API 密钥
|
存储 传感器 编解码
微软行星云计算planet platform中的高分辨率影像通过API接入Google Earth Engine(GEE)
微软行星云计算planet platform中的高分辨率影像通过API接入Google Earth Engine(GEE)
316 0
微软行星云计算planet platform中的高分辨率影像通过API接入Google Earth Engine(GEE)
|
存储 前端开发 JavaScript
Google Earth Engine(GEE)——Qgis-earthengine使用 Python API 集成 Google Earth Engine 和 QGIS
Google Earth Engine(GEE)——Qgis-earthengine使用 Python API 集成 Google Earth Engine 和 QGIS
433 0
Google Earth Engine(GEE)——Qgis-earthengine使用 Python API 集成 Google Earth Engine 和 QGIS