|
| 1 | +using System.Collections.Generic; |
| 2 | +using LukeBot.AWS; |
| 3 | +using LukeBot.Common; |
| 4 | +using LukeBot.Config; |
| 5 | +using Amazon; |
| 6 | +using Amazon.Polly; |
| 7 | +using Amazon.Polly.Model; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using System.IO; |
| 10 | +using System; |
| 11 | +using System.Net; |
| 12 | + |
| 13 | + |
| 14 | +namespace LukeBot.AWS.Impl |
| 15 | +{ |
| 16 | + internal class Polly: IPolly |
| 17 | + { |
| 18 | + private AmazonPollyConfig mConfig; |
| 19 | + private AmazonPollyClient mClient; |
| 20 | + |
| 21 | + private VoiceId PollyVoiceToVoiceId(PollyVoice voice) |
| 22 | + { |
| 23 | + switch (voice) |
| 24 | + { |
| 25 | + case PollyVoice.Brian: return VoiceId.Brian; |
| 26 | + case PollyVoice.Jacek: return VoiceId.Jacek; |
| 27 | + default: throw new ArgumentException(String.Format("Unknown Polly voice requested: {0}", voice)); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + internal Polly() |
| 32 | + { |
| 33 | + Config.Path awsRegionConfPath = Config.Path.Start() |
| 34 | + .Push(Common.Constants.AWS_SERVICE_NAME) |
| 35 | + .Push(Common.Constants.PROP_STORE_REGION_PROP_NAME); |
| 36 | + |
| 37 | + mConfig = new(); |
| 38 | + if (Conf.TryGet<string>(awsRegionConfPath, out string awsRegion)) |
| 39 | + { |
| 40 | + mConfig.RegionEndpoint = RegionEndpoint.GetBySystemName(awsRegion); |
| 41 | + } |
| 42 | + else |
| 43 | + { |
| 44 | + mConfig.RegionEndpoint = RegionEndpoint.EUCentral1; |
| 45 | + } |
| 46 | + |
| 47 | + mClient = new(AWSCredentials.ID, AWSCredentials.Secret, mConfig); |
| 48 | + } |
| 49 | + |
| 50 | + public async Task<Stream> SynthesizeSpeech(PollyVoice voice, string text) |
| 51 | + { |
| 52 | + SynthesizeSpeechRequest request = new(); |
| 53 | + request.OutputFormat = OutputFormat.Ogg_vorbis; |
| 54 | + request.Engine = Engine.Standard; |
| 55 | + request.VoiceId = PollyVoiceToVoiceId(voice); |
| 56 | + request.SampleRate = "44100"; |
| 57 | + request.Text = text; |
| 58 | + |
| 59 | + SynthesizeSpeechResponse response = await mClient.SynthesizeSpeechAsync(request); |
| 60 | + if (response.HttpStatusCode != HttpStatusCode.OK) |
| 61 | + { |
| 62 | + throw new PollyException("SynthesizeSpeech API returned code {0} ({1})", response.HttpStatusCode, (int)response.HttpStatusCode); |
| 63 | + } |
| 64 | + |
| 65 | + return response.AudioStream; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments