package midware.util.helper; import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.Map; @Slf4j public class TtsHelper { private static void transfer(String word, String filePath) { String type=SpringHelper.getRequiredProperty("common.tts.type"); switch (type) { case "ekho": try { String command = "ekho " + word + " -o " + filePath; Process process = Runtime.getRuntime().exec(command); process.waitFor(); } catch (IOException | InterruptedException ex) { log.error("ekho异常", ex); } break; case "modelscope": Map param = new HashMap<>(); param.put("input", word); Map param1 = new HashMap<>(); param1.put("voice", "zhitian_emo"); param.put("parameters", param1); String url=SpringHelper.getRequiredProperty("common.tts.url"); String result = HttpHelper.post(url, JSON.toJSONString(param)); if (StringHelper.isNotEmpty(result)) { try { Map map = JSON.parseObject(result, Map.class); byte[] bytes = Base64.getDecoder().decode(map.get("output_wav").toString()); File file = new File(filePath); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(bytes); outputStream.close(); } catch (Exception ex) { log.error("modelscope异常", ex); } } break; } } public static String TextToSpeech(String word) { return TextToSpeech(word, ""); } public static String TextToSpeech(String word, String filename) { String parentPath = "files/audio/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()); File file = new File(parentPath); if (!file.exists()) { file.mkdirs(); } if (StringHelper.isEmpty(filename)) { filename = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); } String filePath = file.getAbsolutePath() + "/" + filename + ".wav"; transfer(word,filePath); return filePath; } public static String TextToSpeechWord(String word, String filename) { String parentPath = "files/audio/" ; File file = new File(parentPath); if (!file.exists()) { file.mkdirs(); } String filePath = file.getAbsolutePath() + "/" + filename + ".wav"; if (!new File(filePath).exists()) { transfer(word,filePath); } return filePath; } public static String TextToSpeechAgent(String word, String filename) { String parentPath = "files/agent/"; File file = new File(parentPath); if (!file.exists()) { file.mkdirs(); } String filePath = file.getAbsolutePath() + "/" + filename + ".wav"; // if (!new File(filePath).exists()) { // transfer(word,filePath); // } return filePath; } public static String TextToSpeechPosition(String word, String filename) { String parentPath = "files/position/"; File file = new File(parentPath); if (!file.exists()) { file.mkdirs(); } String filePath = file.getAbsolutePath() + "/" + filename + ".wav"; // if (!new File(filePath).exists()) { // transfer(word,filePath); // } return filePath; } }