AWS - Amazon Polly发表演讲

时间:2017-04-08 15:06:55

标签: c# amazon-web-services text-to-speech amazon-polly

我对“文字转语音” Amazon Polly 服务表示怀疑。
我已经在聊天机器人中集成了这项服务,以便用声音描述机器人在聊天中写给用户的内容。
它运作得很好,但我不知道是否有可能提前停止声音,然后(我选择了一个女声)完成说话。有时候我需要在谈话中更进一步,直到句子结束我都不想听。

这是用于整合的代码:

//Html side
function textToSpeech(text) {
  $.ajax({
    type: 'GET',
    url: '/Chat/TextToSpeech?text=' + text,
    
    cache: false,
    success: function (result) {
    
      var audio = document.getElementById('botvoice');
      $("#botvoice").attr("src", "/Audios/" + result);
      audio.load();                 
      audio.play();
    }
  });
}

控制器端:

public ActionResult TextToSpeech(string text)
{
    string filename = "";
    try
    {
        AWSCredentials credentials = new StoredProfileAWSCredentials("my_credential");
        AmazonPollyClient client = new AmazonPollyClient(credentials, Amazon.RegionEndpoint.EUWest1);

        // Create describe voices request.
        DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
        // Synchronously ask Amazon Polly to describe available TTS voices.
        DescribeVoicesResponse describeVoicesResult = client.DescribeVoices(describeVoicesRequest);
        List<Voice> voices = describeVoicesResult.Voices;


        // Create speech synthesis request.
        SynthesizeSpeechRequest synthesizeSpeechPresignRequest = new SynthesizeSpeechRequest();
        // Text
        synthesizeSpeechPresignRequest.Text = text;
        // Select voice for synthesis.
        synthesizeSpeechPresignRequest.VoiceId = voices[18].Id;
        // Set format to MP3.
        synthesizeSpeechPresignRequest.OutputFormat = OutputFormat.Mp3;
        // Get the presigned URL for synthesized speech audio stream.

        string current_dir = AppDomain.CurrentDomain.BaseDirectory;
        filename = CalculateMD5Hash(text) + ".mp3";
        var path_audio = current_dir + @"\Audios\" + filename;

        var presignedSynthesizeSpeechUrl = client.SynthesizeSpeechAsync(synthesizeSpeechPresignRequest).GetAwaiter().GetResult();

        FileStream wFile = new FileStream(path_audio, FileMode.Create);
        presignedSynthesizeSpeechUrl.AudioStream.CopyTo(wFile);
        wFile.Close();
    }
    catch (Exception ex)
    {
        filename = ex.ToString();
    }

    return Json(filename, JsonRequestBehavior.AllowGet);
}

我的聊天(显然)中存在输入文本,用于写入和发送(通过按键盘上的ENTER)问题到机器人。我试图将命令audio.src=""放在处理程序中,然后她停止说话,但聊天仍然被阻止......似乎它等待音频流的结束。我必须刷新页面才能看到新消息和响应。

我是否可以使用特定参数集调用任何Amazon函数,以便通知服务我要停止并清除音频流?

2 个答案:

答案 0 :(得分:3)

Amazon Polly返回.mp3个文件。它不负责播放音频文件。

您遇到播放/停止音频的任何困难都是您用来播放MP3音频文件的代码的结果。它与Amazon Polly服务本身无关。

答案 1 :(得分:0)

谢谢!我发现了真正的问题:当我停止播放音频时,我没有打印其余的信息。我将调用添加到在聊天中打印消息的函数。为了停止声音我使用了命令audio.src =&#34;&#34 ;;