调用api实现TTS
注:如对api的使用有任何疑问,可以查阅文本转语音 REST API。
-
选择右侧“解决方案资源管理器”中的“TTS_Demo”,右键选择“添加”->“新建项”。
选择“类”,名称为“Authentication.cs”,点击“添加”。
-
在 Authentication.cs 文件中,引用如下命名空间。
using System.Net.Http; using System.IO;
添加如下代码。
namespace TTS_Demo { public class Authentication { private string subscriptionKey; private string tokenFetchUri; public Authentication(string tokenFetchUri, string subscriptionKey) { if (string.IsNullOrWhiteSpace(tokenFetchUri)) { throw new ArgumentNullException(nameof(tokenFetchUri)); } if (string.IsNullOrWhiteSpace(subscriptionKey)) { throw new ArgumentNullException(nameof(subscriptionKey)); } this.tokenFetchUri = tokenFetchUri; this.subscriptionKey = subscriptionKey; } public async Task<string> FetchTokenAsync() { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", this.subscriptionKey); UriBuilder uriBuilder = new UriBuilder(this.tokenFetchUri); var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null).ConfigureAwait(false); return await result.Content.ReadAsStringAsync().ConfigureAwait(false); } } } }
-
同理,新建类文件 TTSApi.cs,并添加如下代码。
namespace TTS_Demo { class TTSApi { //语言配置信息 string locale = "zh-CN"; string voiceName = "Microsoft Server Speech Text to Speech Voice (zh-CN, HuihuiRUS)"; string accessToken; Authentication auth = new Authentication("https://westus.api.cognitive.microsoft.com/sts/v1.0/issuetoken", "REPLACE_WITH_YOUR_KEY"); string host = "https://westus.tts.speech.microsoft.com/cognitiveservices/v1"; //转换文本并保存 public async Task textToSpeechAsync(string text, string savePath) { try { accessToken = await auth.FetchTokenAsync().ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine(ex); } string body = "<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='"+locale+"'>" +"<voice n