// Clear all clips in a tts preload file public static void DeleteData(TTSService service) { // Get test file path string path = service.GetDiskCachePath(string.Empty, "TEST", null, new TTSDiskCacheSettings() { DiskCacheLocation = TTSDiskCacheLocation.Preload }); // Get directory string directory = new FileInfo(path).DirectoryName; if (!Directory.Exists(directory)) { return; } // Ask if (!EditorUtility.DisplayDialog("Delete Preload Cache", $"Are you sure you would like to delete the TTS Preload directory at:\n{directory}?", "Okay", "Cancel")) { return; } // Delete recursively Directory.Delete(directory, true); // Delete meta string meta = directory + ".meta"; if (File.Exists(meta)) { File.Delete(meta); } // Refresh assets AssetDatabase.Refresh(); }
// Iterate phrases private static void IteratePhrases(TTSService service, TTSPreloadData preloadData, TTSPreloadIterateDelegate onIterate, Action <float> onProgress, Action <string> onComplete) { // No service if (service == null) { onComplete?.Invoke("\nNo TTSService found in current scene"); return; } // No preload data if (preloadData == null) { onComplete?.Invoke("\nTTS Preload Data Not Found"); return; } // Ignore if running if (Application.isPlaying) { onComplete?.Invoke("Cannot preload while running"); return; } // Unload previous coroutine performer if (_performer != null) { MonoBehaviour.DestroyImmediate(_performer.gameObject); _performer = null; } // Run new coroutine _performer = CoroutineUtility.StartCoroutine(PerformIteratePhrases(service, preloadData, onIterate, onProgress, onComplete)); }
// Refresh private static IEnumerator RefreshPhraseData(TTSService service, TTSDiskCacheSettings cacheSettings, TTSVoiceSettings voiceSettings, TTSPreloadPhraseData phraseData, Action <float> onProgress, Action <string> onComplete) { RefreshPhraseData(service, cacheSettings, voiceSettings, phraseData); yield return(null); onComplete?.Invoke(string.Empty); }
// Refresh phrase data public static void RefreshPhraseData(TTSService service, TTSDiskCacheSettings cacheSettings, TTSVoiceSettings voiceSettings, TTSPreloadPhraseData phraseData) { // Get voice settings if (service == null || voiceSettings == null || string.IsNullOrEmpty(phraseData.textToSpeak)) { phraseData.clipID = string.Empty; phraseData.downloaded = false; phraseData.downloadProgress = 0f; return; } if (cacheSettings == null) { cacheSettings = new TTSDiskCacheSettings() { DiskCacheLocation = TTSDiskCacheLocation.Preload }; } // Get phrase data phraseData.clipID = service.GetClipID(phraseData.textToSpeak, voiceSettings); // Check if file exists string path = service.GetDiskCachePath(phraseData.textToSpeak, phraseData.clipID, voiceSettings, cacheSettings); phraseData.downloaded = File.Exists(path); phraseData.downloadProgress = phraseData.downloaded ? 1f : 0f; }
// Preload voice text private static IEnumerator PreloadPhraseData(TTSService service, TTSDiskCacheSettings cacheSettings, TTSVoiceSettings voiceSettings, TTSPreloadPhraseData phraseData, Action <float> onProgress, Action <string> onComplete) { // Begin running bool running = true; // Download string log = string.Empty; service.DownloadToDiskCache(phraseData.textToSpeak, string.Empty, voiceSettings, cacheSettings, delegate(TTSClipData data, string path, string error) { // Set phrase data phraseData.clipID = data.clipID; phraseData.downloaded = string.IsNullOrEmpty(error); // Failed if (!phraseData.downloaded) { log += $"\n-{voiceSettings.settingsID} Preload Failed: {phraseData.textToSpeak}"; } // Next running = false; }); // Wait for running to complete while (running) { //Debug.Log($"Preload Wait: {voiceSettings.settingsID} - {phraseData.textToSpeak}"); yield return(null); } // Invoke onComplete?.Invoke(log); }
// Refresh voices private void RefreshVoices() { // Reset voice data _voiceIndex = -1; _voices = null; // Get settings TTSService tts = TTSService.Instance; TTSVoiceSettings[] settings = tts?.GetAllPresetVoiceSettings(); if (settings == null) { Debug.LogError("No Preset Voice Settings Found!"); return; } // Apply all settings _voices = new string[settings.Length]; for (int i = 0; i < settings.Length; i++) { _voices[i] = settings[i].settingsID; if (string.Equals(_speaker.presetVoiceID, _voices[i], StringComparison.CurrentCultureIgnoreCase)) { _voiceIndex = i; } } }
public (bool status, WeatherData response) GetWeatherInfo(string apiKey, int pinCode = 689653, string countryCode = "in", bool withTTS = true) { if (!Core.IsNetworkAvailable) { Logger.Log("Cannot continue as network isn't available.", LogLevels.Warn); return(false, WeatherResult); } if (Helpers.IsNullOrEmpty(apiKey)) { return(false, WeatherResult); } if (pinCode <= 0 || Helpers.IsNullOrEmpty(countryCode)) { return(false, WeatherResult); } (bool status, ApiResponseStructure.Rootobject response) = FetchWeatherInfo(apiKey, pinCode, countryCode); if (status) { WeatherResult.Latitude = response.coord.lat; WeatherResult.Logitude = response.coord.lon; WeatherResult.Temperature = response.main.temp; WeatherResult.WeatherMain = response.weather[0].main; WeatherResult.WeatherIcon = response.weather[0].icon; WeatherResult.WeatherDescription = response.weather[0].description; WeatherResult.Pressure = response.main.pressure; WeatherResult.Humidity = response.main.humidity; WeatherResult.SeaLevel = response.main.sea_level; WeatherResult.GroundLevel = response.main.grnd_level; WeatherResult.WindSpeed = response.wind.speed; WeatherResult.WindDegree = response.wind.deg; WeatherResult.Clouds = response.clouds.all; WeatherResult.TimeZone = response.timezone; WeatherResult.LocationName = response.name; if (withTTS) { Helpers.InBackgroundThread(async() => { await TTSService.SpeakText($"Sir, The weather at {pinCode} is...", true).ConfigureAwait(false); await TTSService.SpeakText($"Temperature is {WeatherResult.Temperature}").ConfigureAwait(false); await TTSService.SpeakText($"Humidity is {WeatherResult.Humidity}").ConfigureAwait(false); await TTSService.SpeakText($"Pressure is {WeatherResult.Pressure}").ConfigureAwait(false); await TTSService.SpeakText($"Sea Level is {WeatherResult.SeaLevel}").ConfigureAwait(false); await TTSService.SpeakText($"Wind Speed is {WeatherResult.WindSpeed}").ConfigureAwait(false); await TTSService.SpeakText($"And the location name is {WeatherResult.LocationName}").ConfigureAwait(false); await TTSService.SpeakText($"and thats all sir!").ConfigureAwait(false); }); } return(true, WeatherResult); } else { Logger.Log("failed to assign weather info values", LogLevels.Trace); return(false, WeatherResult); } }
// 插件停用 public override void Stop() { base.Stop(); //請勿使用任何阻塞方法 AudioService.playStoppedEvent -= onPlayFinished; AudioService.uninit(); TTSService.uninit(); }
// Get voice ids private List <string> GetVoiceIDs(TTSService service) { List <string> results = new List <string>(); if (service != null) { foreach (var voiceSetting in service.GetAllPresetVoiceSettings()) { if (voiceSetting != null && !string.IsNullOrEmpty(voiceSetting.settingsID) && !results.Contains(voiceSetting.settingsID)) { results.Add(voiceSetting.settingsID); } } } return(results); }
// 开始文本转语音 void translateTTSTask(TTSTask task) { task.state = TTSTask.State.Translating; if (needInitTTS) { needInitTTS = false; TTSService.uninit(); string secretId = config.useCustomSecret ? config.secretId : TencentSecret.secretId; string secretKey = config.useCustomSecret ? config.secretKey : TencentSecret.secretKey; TTSService.init(secretId, secretKey); } TTSService.translate(task.text, config.volume, (int)config.speed, (int)config.voiceType, (text, audioData, err) => { onTranslateFinished(err, task, audioData); }); }
private static void OnServiceGUI(TTSService service) { // Wrong type if (service.GetType() != typeof(TTSWit) || Application.isPlaying) { return; } // Get data string text = "Update Voice List"; bool canUpdate = true; if (IsUpdating) { text = "Updating Voice List"; canUpdate = false; } else if (IsLoading) { text = "Loading Voice List"; canUpdate = false; } // Layout update GUI.enabled = canUpdate; if (WitEditorUI.LayoutTextButton(text) && canUpdate) { TTSWit wit = service as TTSWit; UpdateVoices(wit.RequestSettings.configuration, null); } GUI.enabled = true; // Force an update if (!_forcedUpdate && canUpdate && (_voices == null || _voices.Length == 0)) { _forcedUpdate = true; TTSWit wit = service as TTSWit; UpdateVoices(wit.RequestSettings.configuration, null); } }
private void OnScheduledTimeReached(object sender, ScheduledTaskEventArgs e) { if (Alarms.Count <= 0) { return; } foreach (Alarm alarm in Alarms) { if (alarm.AlarmGuid == e.Guid) { Logger.Log($"ALARM >>> {alarm.AlarmMessage}"); if (alarm.ShouldUseTTS) { Task.Run(async() => await TTSService.SpeakText($"Sir, {alarm.AlarmMessage}", true).ConfigureAwait(false)); } Helpers.InBackgroundThread(async() => await PlayAlarmSound(alarm.AlarmGuid).ConfigureAwait(false)); alarm.IsCompleted = true; if (!alarm.ShouldRepeat) { foreach (SchedulerConfig task in Core.Scheduler.Configs) { if (task.Guid == e.Guid) { if (task.SchedulerTimer != null) { task.SchedulerTimer.Dispose(); } } } } return; } } }
// Refresh phrase data public static void RefreshVoiceData(TTSService service, TTSPreloadVoiceData voiceData, TTSDiskCacheSettings cacheSettings, ref string log) { // Get voice settings if (service == null) { log += "\n-No TTS service found"; return; } // No voice data if (voiceData == null) { log += "\n-No voice data provided"; return; } // Get voice TTSVoiceSettings voiceSettings = service.GetPresetVoiceSettings(voiceData.presetVoiceID); if (voiceSettings == null) { log += "\n-Missing Voice Setting: " + voiceData.presetVoiceID; return; } // Generate if (cacheSettings == null) { cacheSettings = new TTSDiskCacheSettings() { DiskCacheLocation = TTSDiskCacheLocation.Preload }; } // Iterate phrases for (int p = 0; p < voiceData.phrases.Length; p++) { RefreshPhraseData(service, cacheSettings, voiceSettings, voiceData.phrases[p]); } }
public PhraseApi(PhraseService phraseService, TTSService tts) { PhraseService = phraseService; }
void translator_SpeakCompleted(object sender, TTSService.SpeakCompletedEventArgs e) { var client = new WebClient(); client.OpenReadCompleted += ((s, args) => { SoundEffect se = SoundEffect.FromStream(args.Result); se.Play(); }); client.OpenReadAsync(new Uri(e.Result)); }
// GUI public override void OnInspectorGUI() { // Display default ui base.OnInspectorGUI(); // Get service if (_service == null) { _service = target as TTSService; } // Add additional gui onAdditionalGUI?.Invoke(_service); // Ignore if in editor if (!Application.isPlaying) { return; } // Add spaces EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.LabelField("Runtime Clip Cache", EditorStyles.boldLabel); // No clips TTSClipData[] clips = _service.GetAllRuntimeCachedClips(); if (clips == null || clips.Length == 0) { WitEditorUI.LayoutErrorLabel("No clips found"); return; } // Has clips _clipFoldout = WitEditorUI.LayoutFoldout(new GUIContent($"Clips: {clips.Length}"), _clipFoldout); if (_clipFoldout) { EditorGUI.indentLevel++; // Iterate clips foreach (TTSClipData clip in clips) { // Get display name string displayName = clip.textToSpeak; // Crop if too long if (displayName.Length > MAX_DISPLAY_TEXT) { displayName = displayName.Substring(0, MAX_DISPLAY_TEXT); } // Add voice setting id if (clip.voiceSettings != null) { displayName = $"{clip.voiceSettings.settingsID} - {displayName}"; } // Foldout if desired bool foldout = WitEditorUI.LayoutFoldout(new GUIContent(displayName), clip); if (foldout) { EditorGUI.indentLevel++; OnClipGUI(clip); EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } }
// Layout Preload Data protected virtual void LayoutPreloadActions() { // Layout preload actions EditorGUILayout.Space(); WitEditorUI.LayoutSubheaderLabel("TTS Preload Actions"); // Indent EditorGUI.indentLevel++; EditorGUILayout.Space(); // Hide when playing if (Application.isPlaying) { EditorUtility.ClearProgressBar(); WitEditorUI.LayoutErrorLabel("TTS preload actions cannot be performed at runtime."); EditorGUI.indentLevel--; return; } // Get TTS Service if needed TtsService = EditorGUILayout.ObjectField("TTS Service", TtsService, typeof(TTSService), true) as TTSService; if (TtsService == null) { EditorUtility.ClearProgressBar(); TtsService = GameObject.FindObjectOfType <TTSService>(); WitEditorUI.LayoutErrorLabel("You must add a TTS Service to the loaded scene in order perform TTS actions."); EditorGUI.indentLevel--; return; } if (TtsService != null && _ttsVoiceIDs == null) { _ttsVoiceIDs = GetVoiceIDs(TtsService); } // Begin buttons EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); // Import JSON GUILayout.Space(ACTION_BTN_INDENT * EditorGUI.indentLevel); if (WitEditorUI.LayoutTextButton("Refresh Data")) { RefreshData(); } GUILayout.Space(ACTION_BTN_INDENT); if (WitEditorUI.LayoutTextButton("Import JSON")) { EditorUtility.ClearProgressBar(); if (TTSPreloadUtility.ImportData(Settings)) { RefreshData(); } } // Clear disk cache GUI.enabled = TtsService != null; EditorGUILayout.Space(); Color col = GUI.color; GUI.color = Color.red; if (WitEditorUI.LayoutTextButton("Delete Cache")) { EditorUtility.ClearProgressBar(); TTSPreloadUtility.DeleteData(TtsService); RefreshData(); } // Preload disk cache GUILayout.Space(ACTION_BTN_INDENT); GUI.color = Color.green; if (WitEditorUI.LayoutTextButton("Preload Cache")) { DownloadClips(); } GUI.color = col; GUI.enabled = true; // End buttons EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); // Indent EditorGUI.indentLevel--; }
// Refresh public static void RefreshPreloadData(TTSService service, TTSPreloadData preloadData, Action <float> onProgress, Action <TTSPreloadData, string> onComplete) { IteratePhrases(service, preloadData, RefreshPhraseData, onProgress, (l) => onComplete?.Invoke(preloadData, l)); }
// Perform iterate private static IEnumerator PerformIteratePhrases(TTSService service, TTSPreloadData preloadData, TTSPreloadIterateDelegate onIterate, Action <float> onProgress, Action <string> onComplete) { // Get cache settings TTSDiskCacheSettings cacheSettings = new TTSDiskCacheSettings() { DiskCacheLocation = TTSDiskCacheLocation.Preload }; // Get total phrases int phraseTotal = 0; foreach (var voice in preloadData.voices) { if (voice.phrases == null) { continue; } foreach (var phrase in voice.phrases) { phraseTotal++; } } // Begin onProgress?.Invoke(0f); // Iterate int phraseCount = 0; float phraseInc = 1f / (float)phraseTotal; string log = string.Empty; for (int v = 0; v < preloadData.voices.Length; v++) { // Get voice data TTSPreloadVoiceData voiceData = preloadData.voices[v]; // Get voice TTSVoiceSettings voiceSettings = service.GetPresetVoiceSettings(voiceData.presetVoiceID); if (voiceSettings == null) { log += "\n-Missing Voice Setting: " + voiceData.presetVoiceID; phraseCount += voiceData.phrases.Length; continue; } // Iterate phrases for (int p = 0; p < voiceData.phrases.Length; p++) { // Iterate progress float progress = (float)phraseCount / (float)phraseTotal; onProgress?.Invoke(progress); phraseCount++; // Iterate yield return(onIterate(service, cacheSettings, voiceSettings, voiceData.phrases[p], (p2) => onProgress?.Invoke(progress + p2 * phraseInc), (l) => log += l)); } } // Complete onProgress?.Invoke(1f); onComplete?.Invoke(log); }