|
|
@@ -0,0 +1,57 @@
|
|
|
+package com.wj.utils;
|
|
|
+
|
|
|
+import com.wj.DTO.RecordingInfo;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.bytedeco.javacpp.Loader;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.Optional;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+public class AudioTransferWavUtils {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据RecordingInfo信息转换音频为标准wav格式
|
|
|
+ *
|
|
|
+ * @param info 包含录音信息的RecordingInfo对象
|
|
|
+ * @param baseDir 存储录音文件的基础目录
|
|
|
+ * @return 标准wav格式的文件路径
|
|
|
+ * @throws Exception 转换异常
|
|
|
+ */
|
|
|
+ public static String transferAudio(RecordingInfo info, String baseDir) throws Exception {
|
|
|
+ String transferDirectory = baseDir + File.separator + "audio_transfers";
|
|
|
+ FileUtils.createDirectoryIfNotExists(transferDirectory);
|
|
|
+ // 构建原始录音文件的完整路径
|
|
|
+ String originalFilePath = baseDir + File.separator + info.getFileName();
|
|
|
+ // 构建转换后的文件路径
|
|
|
+ String transferPath = baseDir + File.separator + "audio_transfers" + File.separator + info.getFileName() + ".wav";
|
|
|
+
|
|
|
+ Optional<String> transPath = transferWavStandard(originalFilePath, transferPath);
|
|
|
+ if (transPath.isPresent()) {
|
|
|
+ return transPath.get();
|
|
|
+ } else {
|
|
|
+ throw new Exception("音频转换失败");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 使用ffmpeg将音频转换为标准wav格式
|
|
|
+ *
|
|
|
+ * @param oldFilePath 原音频文件路径
|
|
|
+ * @param newFilePath 转换后的文件路径
|
|
|
+ * @return 转换后的文件路径
|
|
|
+ */
|
|
|
+ public static Optional<String> transferWavStandard(String oldFilePath, String newFilePath) {
|
|
|
+ String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class); // 加载ffmpeg
|
|
|
+ ProcessBuilder transferBuilder = new ProcessBuilder(
|
|
|
+ ffmpeg, "-i", oldFilePath, "-f", "wav", "-ar", "16000", "-ac", "1", "-y", newFilePath);
|
|
|
+ try {
|
|
|
+ transferBuilder.inheritIO().start().waitFor(); // 执行转换命令
|
|
|
+ } catch (InterruptedException | IOException e) {
|
|
|
+ log.error("ffmpeg转换wav为标准格式异常", e);
|
|
|
+ return Optional.empty();
|
|
|
+ }
|
|
|
+ return Optional.of(newFilePath);
|
|
|
+ }
|
|
|
+}
|