예제 #1
0
        public GoogleSpeechSynthesizer(IOptions <GoogleCredentialOptions> googleCredentialOptions)
        {
            if (googleCredentialOptions == null)
            {
                throw new ArgumentNullException(nameof(googleCredentialOptions));
            }

            var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(googleCredentialOptions.Value));

            var builder = new TextToSpeechClientBuilder();

            builder.ChannelCredentials = credentials.ToChannelCredentials();
            _client = builder.Build();
        }
        public TtsBot(ILogger <TtsBot> logger, Option option, AdminAccess.AdminAccess.AdminAccessClient grpcClient, DataStore store)
        {
            _option       = option ?? throw new ArgumentNullException(nameof(option));
            _grpcClient   = grpcClient ?? throw new ArgumentNullException(nameof(grpcClient));
            _store        = store ?? throw new ArgumentNullException(nameof(store));
            _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
            _tweetIdRegex = new Regex(@"\/(?<tweetId>\d+)");

            if (option.GoogleUseEnvironmentVariable)
            {
                _ttsClient = TextToSpeechClient.Create();
            }
            else
            {
                if (string.IsNullOrWhiteSpace(_option.GoogleApplicationCredentialsPath))
                {
                    throw new ArgumentNullException(nameof(_option.GoogleApplicationCredentialsPath), "Credential path cannot be empty if not using Enviornment Variable \"GOOGLE_APPLICATION_CREDENTIALS\"");
                }

                TextToSpeechClientBuilder builder = new TextToSpeechClientBuilder();
                builder.CredentialsPath = _option.GoogleApplicationCredentialsPath;

                _ttsClient = builder.Build();
            }

            _discord      = new DiscordSocketClient();
            _discord.Log += obj =>
            {
                _logger.LogDebug("{0}", obj);
                return(Task.CompletedTask);
            };

            _userCredentials = Auth.CreateCredentials(option.TwitterConsumerKey,
                                                      option.TwitterConsumerSecret,
                                                      option.TwitterUserAccessToken,
                                                      option.TwitterUserAccessSecret);
            Auth.SetCredentials(_userCredentials);

            _stream = TwitterStream.CreateFilteredStream(_userCredentials, TweetMode.Extended);
            _stream.MatchingTweetReceived += OnMatchingTweetReceived;

            foreach (var user in _store.Users)
            {
                _stream.AddFollow(user.Id);
            }

            _store.UsersChanged += OnUserAddedToDataStore;
        }
예제 #3
0
        public GoogleTranslationOptionsRetriever(ILogger <GoogleTranslationOptionsRetriever> logger,
                                                 IOptions <GoogleCredentialOptions> googleCredentialOptions)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (googleCredentialOptions == null)
            {
                throw new ArgumentNullException(nameof(googleCredentialOptions));
            }

            var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(googleCredentialOptions.Value));

            var builder = new TextToSpeechClientBuilder();

            builder.ChannelCredentials = credentials.ToChannelCredentials();

            _logger = logger;
            _client = builder.Build();
        }
        public TTSRenderer(
            ICommunication communication,
            ISoundEffectSystem soundEffectSystem)
        {
            this.communication     = communication;
            this.soundEffectSystem = soundEffectSystem;

            //
            // Prepare Google TTS
            //
            TextToSpeechClientBuilder builder = new TextToSpeechClientBuilder();

            string googleCredentialsPath = BGC.IO.DataManagement.PathForDataFile("Config", "googleCloudCredentials.json");

            if (!File.Exists(googleCredentialsPath))
            {
                throw new FileNotFoundException($"Could not find credentials for Google TTS at {googleCredentialsPath}");
            }

            builder.CredentialsPath = googleCredentialsPath;
            googleClient            = builder.Build();

            //
            // Prepare Amazon TTS
            //
            string awsCredentialsPath = BGC.IO.DataManagement.PathForDataFile("Config", "awsPollyCredentials.json");

            if (!File.Exists(awsCredentialsPath))
            {
                throw new FileNotFoundException($"Could not find credentials for AWS Polly at {awsCredentialsPath}");
            }

            AWSPollyCredentials awsPolyCredentials = JsonSerializer.Deserialize <AWSPollyCredentials>(File.ReadAllText(awsCredentialsPath));

            Amazon.Runtime.BasicAWSCredentials awsCredentials = new Amazon.Runtime.BasicAWSCredentials(
                awsPolyCredentials.AccessKey,
                awsPolyCredentials.SecretKey);

            amazonClient = new AmazonPollyClient(awsCredentials, Amazon.RegionEndpoint.USWest1);
        }
예제 #5
0
        public SpeechSynthesizer()
        {
            // TTS won't work without Discord auth
            if (DiscordOAuth.firebaseCred == null)
            {
                return;
            }

            // Instantiate a client
            TextToSpeechClientBuilder builder = new TextToSpeechClientBuilder
            {
                JsonCredentials = DiscordOAuth.firebaseCred
            };

            client = builder.Build();

            ttsThread = new Thread(TTSThread);
            ttsThread.IsBackground = true;
            ttsThread.Start();


            #region Set up the event listeners to actually use TTS

            Program.PlayerJoined += (frame, team, player) =>
            {
                if (Settings.Default.playerJoinTTS)
                {
                    Program.synth.SpeakAsync($"{player.name} {Resources.tts_join_1} {team.color} {Resources.tts_join_2}");
                }
            };
            Program.PlayerLeft += (frame, team, player) =>
            {
                if (Settings.Default.playerLeaveTTS)
                {
                    Program.synth.SpeakAsync($"{player.name} {Resources.tts_leave_1} {team.color} {Resources.tts_leave_2}");
                }
            };
            Program.PlayerSwitchedTeams += (frame, fromTeam, toTeam, player) =>
            {
                if (!Settings.Default.playerSwitchTeamTTS)
                {
                    return;
                }

                if (fromTeam != null)
                {
                    Program.synth.SpeakAsync($"{player.name} {Resources.tts_switch_1} {fromTeam.color} {Resources.tts_switch_2} {toTeam.color} {Resources.tts_switch_3}");
                }
                else
                {
                    Program.synth.SpeakAsync($"{player.name} {Resources.tts_switch_alt_1} {toTeam.color} {Resources.tts_switch_alt_2}");
                }
            };
            Program.PauseRequest += (frame) =>
            {
                if (Settings.Default.pausedTTS)
                {
                    Program.synth.SpeakAsync($"{frame.pause.paused_requested_team} {Resources.tts_pause_req}");
                }
            };
            Program.GamePaused += (frame) =>
            {
                if (Settings.Default.pausedTTS)
                {
                    Program.synth.SpeakAsync($"{frame.pause.paused_requested_team} {Resources.tts_paused}");
                }
            };
            Program.GameUnpaused += (frame) =>
            {
                if (Settings.Default.pausedTTS)
                {
                    Program.synth.SpeakAsync($"{frame.pause.paused_requested_team} {Resources.tts_unpause}");
                }
            };
            Program.LocalThrow += (frame) =>
            {
                if (Settings.Default.throwSpeedTTS && frame.last_throw.total_speed > 10)
                {
                    Program.synth.SpeakAsync($"{frame.last_throw.total_speed:N1}");
                }
            };
            Program.BigBoost += (frame, team, player, speed, howLongAgo) =>
            {
                if (Settings.Default.maxBoostSpeedTTS && player.name == frame.client_name)
                {
                    Program.synth.SpeakAsync($"{speed:N0} {Resources.tts_meters_per_second}");
                }
            };
            Program.PlayspaceAbuse += (frame, team, player, playspacePos) =>
            {
                if (Settings.Default.playspaceTTS)
                {
                    Program.synth.SpeakAsync($"{player.name} {Resources.tts_abused}");
                }
            };
            Program.Joust += (frame, team, player, isNeutral, joustTime, maxSpeed, maxTubeExitSpeed) =>
            {
                // only joust time
                if (Settings.Default.joustTimeTTS && !Settings.Default.joustSpeedTTS)
                {
                    Program.synth.SpeakAsync($"{team.color} {joustTime:N1}");
                }
                // only joust speed
                else if (!Settings.Default.joustTimeTTS && Settings.Default.joustSpeedTTS)
                {
                    Program.synth.SpeakAsync($"{team.color} {maxSpeed:N0} {Resources.tts_meters_per_second}");
                }
                // both
                else if (Settings.Default.joustTimeTTS && Settings.Default.joustSpeedTTS)
                {
                    Program.synth.SpeakAsync($"{team.color} {joustTime:N1} {maxSpeed:N0} {Resources.tts_meters_per_second}");
                }
            };
            Program.Goal += (frame, goalEvent) =>
            {
                if (Settings.Default.goalDistanceTTS)
                {
                    Program.synth.SpeakAsync($"{frame.last_score.distance_thrown:N1} {Resources.tts_meters}");
                }

                if (Settings.Default.goalSpeedTTS)
                {
                    Program.synth.SpeakAsync($"{frame.last_score.disc_speed:N1} {Resources.tts_meters_per_second}");
                }
            };

            #endregion
        }
예제 #6
0
        public ActionResult TextToSpeech(string text, string lang, string voice, double rate)
        {
            try

            {
                TextToSpeechClient client;
                try
                {
                    client = TextToSpeechClient.Create();
                }
                catch (Exception e)
                {
                    var clientBuilder = new TextToSpeechClientBuilder();
                    clientBuilder.CredentialsPath = Server.MapPath("/Views/key.json");
                    client = clientBuilder.Build();
                }

                // Set the text input to be synthesized.
                SynthesisInput input = new SynthesisInput
                {
                    Text = text
                };

                // Build the voice request, select the language code ("en-US"),
                // and the SSML voice gender ("neutral").
                SsmlVoiceGender gender;
                switch (voice)
                {
                case "0":
                    gender = SsmlVoiceGender.Male;
                    break;

                case "1":
                    gender = SsmlVoiceGender.Female;
                    break;

                default:
                    gender = SsmlVoiceGender.Neutral;
                    break;
                }

                VoiceSelectionParams voiceSel = new VoiceSelectionParams
                {
                    LanguageCode = lang,
                    SsmlGender   = gender,
                };


                // Select the type of audio file you want returned.
                AudioConfig config = new AudioConfig
                {
                    AudioEncoding = AudioEncoding.Mp3,
                    SpeakingRate  = rate,
                };

                // Perform the Text-to-Speech request, passing the text input
                // with the selected voice parameters and audio file type
                var response = client.SynthesizeSpeech(new SynthesizeSpeechRequest
                {
                    Input       = input,
                    Voice       = voiceSel,
                    AudioConfig = config
                });

                // Write the binary AudioContent of the response to an MP3 file.

                return(Content(response.AudioContent.ToBase64()));
            }catch (Exception e)
            {
                return(Content(e.ToString()));
            }
        }
        private byte[] GoogleTTS(string msg)
        {
            try
            {
                TextToSpeechClientBuilder builder = new TextToSpeechClientBuilder
                {
                    CredentialsPath = opts.GoogleCredentials
                };

                TextToSpeechClient client = builder.Build();

                SynthesisInput input = new SynthesisInput
                {
                    Text = msg
                };

                VoiceSelectionParams voice = null;

                if (!string.IsNullOrEmpty(opts.Voice))
                {
                    voice = new VoiceSelectionParams()
                    {
                        Name         = opts.Voice,
                        LanguageCode = opts.Voice.Substring(0, 5),
                    };
                }
                else
                {
                    voice = new VoiceSelectionParams
                    {
                        LanguageCode = opts.Culture,
                    };

                    switch (opts.Gender.ToLowerInvariant().Trim())
                    {
                    case "male":
                        voice.SsmlGender = SsmlVoiceGender.Male;
                        break;

                    case "neutral":
                        voice.SsmlGender = SsmlVoiceGender.Neutral;
                        break;

                    case "female":
                        voice.SsmlGender = SsmlVoiceGender.Female;
                        break;

                    default:
                        voice.SsmlGender = SsmlVoiceGender.Male;
                        break;
                    }
                }

                AudioConfig config = new AudioConfig
                {
                    AudioEncoding   = AudioEncoding.Linear16,
                    SampleRateHertz = INPUT_SAMPLE_RATE
                };

                var response = client.SynthesizeSpeech(new SynthesizeSpeechRequest
                {
                    Input       = input,
                    Voice       = voice,
                    AudioConfig = config
                });

                var tempFile = Path.GetTempFileName();

                using (var stream = File.Create(tempFile))
                {
                    response.AudioContent.WriteTo(stream);
                }

                byte[] bytes = null;
                using (var reader = new WaveFileReader(tempFile))
                {
                    bytes = new byte[reader.Length];
                    var read = reader.Read(bytes, 0, bytes.Length);
                    Logger.Info($"Success with Google TTS - read {read} bytes");
                }

                //cleanup
                File.Delete(tempFile);

                return(bytes);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, $"Error with Google Text to Speech: {ex.Message}");
            }
            return(new byte[0]);
        }