private bool AudioClipDataIsComplete(bool fileGenerationOnly = false)
        {
            bool          allOK = true;
            StringBuilder sb    = new StringBuilder();

            if (!fileGenerationOnly && String.IsNullOrEmpty(AudioClipLabel))
            {
                sb.AppendLine("Please give the audioclip a label.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioClipText))
            {
                sb.AppendLine("Please set the audioclip text.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioFileDirectory))
            {
                sb.AppendLine("Please set a directory for the audio clip.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioFileName))
            {
                sb.AppendLine("Please set a filename.");
                allOK = false;
            }
            if (!allOK)
            {
                var messageWin = new MessageWin("Save Audioclip", sb.ToString());
                messageWin.Show();
            }
            return(allOK);
        }
Exemple #2
0
        public static void CheckAudioFiles()
        {
            // Runs at startup if 'Check Audio files' in Settings screen is checked

            Logger.AddLogEntry(LogCategory.INFO, "Checking audio files...");
            bool allOK = true;

            if (!AudioClipsMgr.CheckAudioFiles())
            {
                allOK = false;
            }
            if (allOK)
            {
                Logger.AddLogEntry(LogCategory.INFO, "Audio files OK");
            }
            else
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    var messageWin = new MessageWin("Audio Files Check", "WARNING: One or more audio files is missing\nCheck Event Log for details.");
                    messageWin.Show();
                }));
                Logger.AddLogEntry(LogCategory.ERROR, "One or more audio files is missing");
            }
        }
        private void RealButton_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("导入失败");
            isFailed = true;
            BarGo();
            MessageWin wm = new MessageWin("已手动停止资源获取,本次导入资源失败。");

            wm.Show(true);
        }
        public static string GenerateSpeech(string audioText)
        {
            /*
             * Generates audio when online;
             * Default fileName is audio text with illegal characters replaced by "_"
             * FileName can be specified to avoid long filenames
             *
             */
            if (!String.IsNullOrEmpty(audioText))
            {
                string credentialsFile = GetCredentialsFile();
                if (!String.IsNullOrEmpty(credentialsFile))
                {
                    try
                    {
                        GoogleCredential         credentials = GoogleCredential.FromFile(credentialsFile);
                        SynthesizeSpeechResponse response;
                        using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                        {
                            response = textToSpeechClient.SynthesizeSpeech(
                                new SynthesisInput()
                            {
                                Text = audioText
                            },
                                new VoiceSelectionParams()
                            {
                                LanguageCode = LanguageCode,
                                Name         = Voice,
                                SsmlGender   = Gender
                            },
                                new AudioConfig()
                            {
                                AudioEncoding   = AudioEncoding.Mp3,
                                SpeakingRate    = (float?)(0.95 * AudioMgr.SpeedRatio), // default speed set to 0.95
                                SampleRateHertz = 24000
                            }
                                );
                        }

                        string speechFile = Path.Combine(DirectoryMgr.TempDirectory, Guid.NewGuid().ToString() + ".mp3");
                        File.WriteAllBytes(speechFile, response.AudioContent);
                        return(speechFile);
                    }
                    catch (Exception e)
                    {
                        Logger.AddLogEntry(LogCategory.ERROR,
                                           String.Format("TextToSpeechMgr: Error reading Google credentials file: {0} ", e.ToString()));
                        var messageWin = new MessageWin("TextToSpeechMgr",
                                                        String.Format("Error reading Google credentials file - audio not generated."));
                        messageWin.Show();
                        return(null);
                    }
                }
            }
            return(null);
        }
 private void SaveChanges(object obj)
 {
     if (AudioClipDataIsComplete())
     {
         int    returnValue;
         string msg = "Audio clip saved.";
         if (SelectedAudioClip == null)
         {
             SelectedAudioClip = new AudioClip();
             newAudioClip      = true;
         }
         SelectedAudioClip.Label          = AudioClipLabel;
         SelectedAudioClip.StateText      = AudioClipText;
         SelectedAudioClip.StateAudioFile = Path.Combine(AudioFileDirectory, AudioFileName);
         SelectedAudioClip.Category       = SelectedCategory;
         SelectedAudioClip.IsVisible      = ClipVisibility.Equals("Visible") ? true : false;
         if (SelectedAudioClip.IsVisible)
         {
             SelectedAudioClip.ButtonColour = ButtonColour;
         }
         else
         {
             SelectedAudioClip.ButtonColour = ColourHelper.HiddenColour;
         }
         if (newAudioClip)
         {
             returnValue = AudioClipsMgr.AddAudioClip(SelectedAudioClip);
             if (returnValue > 0)
             {
                 newAudioClip = false;
             }
         }
         else
         {
             returnValue = AudioClipsMgr.UpdateAudioClipToDB(SelectedAudioClip);
         }
         if (returnValue > 0)
         {
             RefreshAudioClips();
             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AudioClips)));
             EventSystem.Publish(new AudioClipsInventoryChanged());
         }
         if (returnValue == -1)
         {
             msg = "Error: Audio clip label already exists - please choose another label.";
         }
         else if (returnValue == -2)
         {
             msg = "Error: Problem saving audioClip to database.";
         }
         var messageWin = new MessageWin("Save Audioclip", msg);
         messageWin.Show();
     }
 }
        public static bool GenerateAudiofile(string audioText, string fileName)
        {
            /*
             * Method generates audio clips for use offline
             */
            string credentialsFile = GetCredentialsFile();

            if (!String.IsNullOrEmpty(credentialsFile))
            {
                try
                {
                    GoogleCredential         credentials = GoogleCredential.FromFile(credentialsFile);
                    SynthesizeSpeechResponse response;
                    using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                    {
                        response = textToSpeechClient.SynthesizeSpeech(
                            new SynthesisInput()
                        {
                            Text = audioText
                        },
                            new VoiceSelectionParams()
                        {
                            LanguageCode = LanguageCode,
                            Name         = Voice,
                            SsmlGender   = Gender
                        },
                            new AudioConfig()
                        {
                            AudioEncoding   = AudioEncoding.Mp3,
                            SpeakingRate    = (float?)0.95, // default speed set to 0.95
                            SampleRateHertz = 24000
                        }
                            );
                    }
                    // check all required directories exist
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                    string speechFile = Path.Combine(fileName + ".mp3");
                    File.WriteAllBytes(speechFile, response.AudioContent);
                    return(true);
                }
                catch (Exception e)
                {
                    string msg        = String.Format("Error reading Google credentials file - audio file not generated.\n{0} ", e.ToString());
                    var    messageWin = new MessageWin("TextToSpeechMgr", msg);
                    messageWin.Show();
                    Logger.AddLogEntry(LogCategory.ERROR, msg);
                }
            }
            return(false);
        }
        private void SaveSettings(string setting)
        {
            string msg = String.Empty;

            switch (setting)
            {
            case "CheckAudioFiles":
                Settings.CheckAudioFiles = CheckAudioFiles;
                msg = "Check Audio Files option saved.";
                break;

            case "CredentialsFile":
                Settings.CredentialsFile = CredentialsFile;
                msg = "Google Application Credentials file setting saved.";
                break;

            case "MaxLogEntries":
                Settings.MaxLogEntries = MaxLogEntries;
                msg = "Maximum log entries option saved.";
                break;

            case "OnlineVoice":
            case "LanguageCode":
                Settings.LanguageCode = SelectedLanguageCode;
                Settings.OnlineVoice  = SelectedVoice;
                msg = "Online voice options saved.";
                break;
            }
            if (SettingsTableMgr.SaveSettingsToDB())
            {
                if (!String.IsNullOrEmpty(msg))
                {
                    var messageWin = new MessageWin("Save Settings", msg);
                    messageWin.Show();
                }
                Logger.AddLogEntry(LogCategory.INFO, "App options saved.");
            }
            else
            {
                var messageWin = new MessageWin("Save Settings", "Error: problem saving app options.");
                messageWin.Show();
                Logger.AddLogEntry(LogCategory.ERROR, "SaveSettings: Problem saving app options");
            }
        }
        private static string GetCredentialsFile()
        {
            string credentialsFile = Settings.CredentialsFile;

            if (!File.Exists(credentialsFile))
            {
                credentialsFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
                                                                     EnvironmentVariableTarget.User);
                if (!File.Exists(credentialsFile))
                {
                    var messageWin = new MessageWin("TextToSpeechMgr",
                                                    String.Format("TextToSpeechMgr Error: Google credentials file not found"));
                    messageWin.Show();
                    Logger.AddLogEntry(LogCategory.ERROR,
                                       String.Format("TextToSpeechMgr: Google credentials file: not found"));
                    return(null);
                }
            }
            return(credentialsFile);
        }
 private void SaveMaxLogEntries(object obj)
 {
     if (Int32.TryParse(MaxLogEntriesTxt, out int maxEntries))
     {
         if (maxEntries >= 0)
         {
             MaxLogEntries = maxEntries;
             SaveSettings("MaxLogEntries");
         }
         else
         {
             MaxLogEntriesTxt = Settings.MaxLogEntries.ToString();
         }
     }
     else
     {
         MaxLogEntriesTxt = Settings.MaxLogEntries.ToString();
         var messageWin = new MessageWin("App Options", String.Format("{0} is not valid for maximum log entries - please update setting.", MaxLogEntriesTxt));
         messageWin.Show();
     }
 }
        public static void LoadOnlineVoices()
        {
            string credentialsFile = GetCredentialsFile();

            if (!String.IsNullOrEmpty(credentialsFile))
            {
                try
                {
                    GoogleCredential credentials = GoogleCredential.FromFile(credentialsFile);
                    using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                    {
                        Voices        = new List <string>();
                        LanguageCodes = new List <string>();
                        var voices = textToSpeechClient.ListVoices();
                        foreach (var voice in voices)
                        {
                            Voices.Add(String.Format("{0} ({1})", voice.Name, voice.SsmlGender.ToLower()));
                            int    index        = voice.Name.IndexOf('-', voice.Name.IndexOf('-') + 1);
                            string languageCode = voice.Name.Substring(0, index);
                            if (!LanguageCodes.Contains(languageCode))
                            {
                                LanguageCodes.Add(languageCode);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.AddLogEntry(LogCategory.ERROR,
                                       String.Format("TextToSpeechMgr: Error reading Google credentials file: {0} ", e.ToString()));
                    var messageWin = new MessageWin("TextToSpeechMgr",
                                                    String.Format("Error reading Google credentials file - voice list not generated."));
                    messageWin.Show();
                }
                if (Voices != null)
                {
                    OnlineVoicesTableMgr.SaveOnlineVoicesToDB(Voices);
                }
            }
        }
        private void GenerateAudioFile(object obj)
        {
            bool filePathSet = true;
            bool fileNameSet = true;
            bool textSet     = true;

            AudioFileName = Path.GetFileName(AudioFileName);
            if (String.IsNullOrEmpty(AudioClipText))
            {
                textSet = false;
            }
            if (String.IsNullOrEmpty(AudioFileDirectory))
            {
                filePathSet = false;
            }
            if (filePathSet && String.IsNullOrEmpty(AudioFileName))
            {
                if (!String.IsNullOrEmpty(AudioClipLabel))
                {
                    AudioFileName = AudioClipLabel;
                }
                else
                {
                    filePathSet = false;
                }
            }
            if (!filePathSet || !textSet)
            {
                string msg;
                if (!textSet && !fileNameSet)
                {
                    msg = "Please complete the directory, filename and audio text fields.";
                }
                else if (!textSet)
                {
                    msg = "Please enter audio text.";
                }
                else
                {
                    msg = "Please complete the directory and filename fields.";
                }
                var msgWin = new MessageWin("Generate Audio File", msg);
                msgWin.Show();
                return;
            }
            try
            {
                Directory.CreateDirectory(AudioFileDirectory);
            }
            catch (Exception)
            {
                var msgWin = new MessageWin("Generate Audio File", "Please enter a valid directory.");
                msgWin.Show();
                return;
            }
            string fileName = Path.Combine(AudioFileDirectory, AudioFileName);

            if (GoogleTextToSpeechMgr.GenerateAudiofile(AudioClipText, fileName))
            {
                SelectedAudioClip.StateAudioFile = fileName;
                AudioFileName                  = Path.GetFileName(fileName);
                SelectedAudioClip.Label        = AudioClipLabel;
                SelectedAudioClip.StateText    = AudioClipText;
                SelectedAudioClip.ButtonColour = ColourHelper.StatementColour;
                var messageWin = new MessageWin("Generate Audio clip", String.Format("Audio clip {0} generated", fileName));
                messageWin.Show();
                Logger.AddLogEntry(LogCategory.INFO, String.Format("Audio clip {0} generated", fileName));
            }
            else
            {
                var messageWin = new MessageWin("Generate Audio clips", String.Format("Errors encountered generating \"{0}\" audio clip.", SelectedAudioClip.Label));
                messageWin.Show();
                Logger.AddLogEntry(LogCategory.ERROR, String.Format("Error generating \"{0}\" audio clip", SelectedAudioClip.Label));
            }
        }
        private void SaveSession(object obj)
        {
            MessageWin messageWin;
            var        msg = "Session saved.";
            int        ret;

            if (newSession)
            {
                ret = SessionsMgr.AddSession(SessionName, null);
                if (ret < 0)
                {
                    msg = ret == -1
                        ? "Error: Problem saving session to database." :
                          "Error: Session name already exists - please choose another name.";
                    messageWin = new MessageWin("Save Session", msg);
                    messageWin.Show();
                    return;
                }
                else
                {
                    SelectedSession = SessionsMgr.GetSessionCopy(SessionName);
                    msg             = "New session saved.";
                }
            }
            SelectedSession.IsRuleset = IsRuleset;
            string newSessionName = SessionName;

            SelectedSession.SessionName = SessionName;
            selectedSessionName         = SessionName;
            SelectedSession.SessionAudioClipsList.Clear();
            if (SessionClips != null)
            {
                foreach (var sessionClip in SessionClips)
                {
                    SelectedSession.SessionAudioClipsList.Add(sessionClip.ClipId);
                }
            }
            ret = SessionsMgr.UpdateSession(SelectedSession);
            if (ret > 0)
            {
                EventSystem.Publish(new SessionsInventoryChanged());
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SessionNames)));
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedSessionName)));
                ChangeSession(newSessionName);
                EventSystem.Publish(new SessionInventoryChanged()
                {
                    SessionName = newSessionName
                });
            }
            else if (ret == -1)
            {
                msg = "Error: Session name already exists - please choose another name.";
            }
            else if (ret == -2)
            {
                msg = "Error: Problem saving session to database.";
            }
            else
            {
                msg = "Error: Problem saving session audioClips to database.";
            }
            messageWin = new MessageWin("Save Session", msg);
            messageWin.Show();
        }