using CloudBuilder.AI.Entity; using CloudBuilder.AI.Service; using CloudBuilder.Core.DatabaseAccessor.Entity; using CloudBuilder.Core.DependencyInjection.Task; using EdgeTtsSharp; using EdgeTtsSharp.NAudio; using EdgeTtsSharp.Structures; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace CloudBuilder.Topshelf.Task.AI { //task:CharacterTtsTask save_path:D:\NET8\CloudBuilder.Topshelf\mp3 short_name:zh-CN-XiaoxiaoNeural public class CharacterTtsTask : IScheduleTask { private readonly IApplicationService service; public CharacterTtsTask(IApplicationService service) { this.service = service; } public void Run(Dictionary bodyDict) { IAiCharacterService aiService = service.ServiceProvider.GetService(); AiCharacterEntity[] aiCharacters = aiService.FindAll(); string shortName = "zh-CN-XiaoxiaoNeural"; string savePath = string.Empty; if (bodyDict.ContainsKey("short_name")) shortName = bodyDict["short_name"]; if (bodyDict.ContainsKey("save_path")) savePath = bodyDict["save_path"]; int totalLines = aiCharacters.Length; int processedLines = 0; // 已处理行数计数器 int totalValidWords = 0; // 可选:统计有效词总数,用于进度详情 foreach (var c in aiCharacters) { try { processedLines++; TtsAsync(shortName, savePath, c).GetAwaiter().GetResult(); UpdateProgress(processedLines, totalLines, totalValidWords); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } public async System.Threading.Tasks.Task TtsAsync(string shortName, string savePath, AiCharacterEntity aiCharacter) { savePath = Path.Combine(savePath, string.Format("{0}.mp3", aiCharacter.Content)); if (File.Exists(savePath)) return; var voice = await EdgeTts.GetVoice(shortName); await voice.SaveAudioToFile(aiCharacter.Content, savePath); } private static void UpdateProgress(int processed, int total, int validWords) { double progressPercent = (double)processed / total * 100; int progressBarLength = 50; // 进度条总长度 int filledLength = (int)(progressPercent / 100 * progressBarLength); // 构建进度条(如:[██████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░]) string progressBar = "[" + new string('█', filledLength) + new string('░', progressBarLength - filledLength) + "]"; string progressInfo = $"{progressBar} {progressPercent:F2}% | 已处理:{processed}/{total} "; Console.Write($"\r{progressInfo}"); Console.Out.Flush(); } } }