public async Task SyntheticAudio(TtsInputOptions inputOptions, Prosody prosody) { ttsToken = new TtsTokenGenerator(this.apiKey).GetAccessToken(); inputOptions.AuthorizationToken = "Bearer " + ttsToken; TtsSynthesize synthesize = new TtsSynthesize(); synthesize.OnAudioAvailable += SuccessHandler; synthesize.OnError += ErrorHandler; try { await synthesize.Speak(CancellationToken.None, inputOptions, prosody); } catch (Exception ex) { } }
/// <summary> /// 生成 SSML. /// </summary> /// <param name="locale">语种</param> /// <param name="gender">性别</param> /// <param name="name">发音人</param> /// <param name="text">要合成的文本</param> /// <param name="prosody">音律相关参数</param> private string GenerateSsml(string locale, string gender, string name, string text, Prosody prosody) { var ssmlDoc = new XDocument( new XElement("speak", new XAttribute("version", "1.0"), new XAttribute(XNamespace.Xml + "lang", "en-US"), new XElement("break", new XAttribute("time", prosody.time) ), new XElement("voice", new XAttribute(XNamespace.Xml + "lang", locale), new XAttribute(XNamespace.Xml + "gender", gender), new XAttribute("name", name), new XElement("prosody", new XAttribute("rate", prosody.rate), new XAttribute("volume", prosody.volume), new XAttribute("pitch", prosody.pitch), text ) ) ) ); string lll = ssmlDoc.ToString(); return(ssmlDoc.ToString()); }
/// <summary> /// 将指定的文本发送到TTS服务,并将响应音频保存到文件中。 /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task</returns> public Task Speak(CancellationToken cancellationToken, TtsInputOptions inputOptions, Prosody prosody) { client.DefaultRequestHeaders.Clear(); foreach (var header in inputOptions.Headers) { client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); } var genderValue = inputOptions.VoiceType.Equals(Gender.Male) ? "Male" : "Female"; var request = new HttpRequestMessage(HttpMethod.Post, inputOptions.RequestUri) { Content = new StringContent(GenerateSsml(inputOptions.Locale, genderValue, inputOptions.VoiceName, inputOptions.Text, prosody)) }; var httpTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); var saveTask = httpTask.ContinueWith( async(responseMessage, token) => { try { if (responseMessage.IsCompleted && responseMessage.Result != null && responseMessage.Result.IsSuccessStatusCode) { var httpStream = await responseMessage.Result.Content.ReadAsStreamAsync().ConfigureAwait(false); this.AudioAvailable(new GenericEventArgs <Stream>(httpStream)); } else { this.Error(new GenericEventArgs <Exception>(new Exception(String.Format("Service returned {0}", responseMessage.Result.StatusCode)))); } } catch (Exception e) { this.Error(new GenericEventArgs <Exception>(e.GetBaseException())); } finally { responseMessage.Dispose(); request.Dispose(); } }, TaskContinuationOptions.AttachedToParent, cancellationToken); return(saveTask); }