Pārlūkot izejas kodu

音频转化上传

jiayi 1 gadu atpakaļ
vecāks
revīzija
54dd53747c

+ 11 - 0
pom.xml

@@ -73,6 +73,17 @@
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.bytedeco</groupId>
+            <artifactId>javacv-platform</artifactId>
+            <version>1.5.9</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 4 - 1
src/main/java/com/wj/Application.java

@@ -1,5 +1,6 @@
 package com.wj;
 
+import com.wj.utils.AudioTransferWavUtils;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@@ -9,9 +10,11 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 @EnableScheduling
 public class Application {
 
-    public static void main(String[] args)  {
+    public static void main(String[] args) throws Exception {
 
         SpringApplication.run(Application.class, args);
+//        String newMp3Path = AudioTransferWavUtils.transferAudio("C:\\Users\\13491\\Desktop\\realme\\532001001525897.wav", "532001001525897-new8000");
+//        System.out.println(newMp3Path);
     }
 }
 

+ 6 - 1
src/main/java/com/wj/service/ProcessFilesService.java

@@ -6,12 +6,14 @@ import com.wj.exception.CustomXmlParseException;
 import com.wj.service.impl.Determine;
 import com.wj.service.impl.FolderIndex;
 import com.wj.service.impl.XmlProcessor;
+import com.wj.utils.AudioTransferWavUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.nio.file.attribute.FileTime;
 import java.time.LocalDate;
 import java.time.ZoneId;
@@ -68,8 +70,11 @@ public class ProcessFilesService {
                         try {
                             RecordingInfo info = parseXmlFile(xmlPath.toFile());
                             if (info != null) {
+                                // 在上传前转换录音文件为标准的WAV格式
+                                String wavFilePath = AudioTransferWavUtils.transferAudio(info, String.valueOf(dir));
+                                // 确认转换成功后再进行上传
                                 Determine processor = new Determine();
-                                processor.DetermineUpload(xmlPath, today, uploadMode, info);
+                                processor.DetermineUpload(Paths.get(wavFilePath), today, uploadMode, info);
                             }
 
                         } catch (CustomXmlParseException e) {

+ 10 - 1
src/main/java/com/wj/service/impl/Determine.java

@@ -75,6 +75,15 @@ public class Determine {
             throw new CustomXmlParseException("无法解析XML文件或文件名为空: " + xmlPath);
         }
     }
-
+    private void processAudioFile(String wavFilePath) {
+        try {
+            // 在这里执行音频文件的格式处理逻辑
+            // 例如,将wavFilePath的音频文件转换为标准的WAV格式
+            // 然后上传处理后的文件
+            // ...
+        } catch (Exception e) {
+            System.err.println("音频处理失败:" + e.getMessage());
+        }
+    }
 }
 

+ 13 - 11
src/main/java/com/wj/service/impl/SaveRecord.java

@@ -1,7 +1,7 @@
 package com.wj.service.impl;
 
+import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import org.json.JSONArray;
 
 import java.net.HttpURLConnection;
 import java.net.URL;
@@ -9,19 +9,21 @@ import java.nio.charset.StandardCharsets;
 
 public class SaveRecord {
 
-    //private static final String sqlurl = PropertiesConfig.getSqlurl();
-
     public static boolean saverecord(String sqlurl, String ucid, String url)  {
         HttpURLConnection con = null;
         try {
-            // 创建JSON对象并填充数据
-            JSONObject json = new JSONObject();
-            json.put("ucid", ucid);
-            json.put("url", url);
-            // 创建一个空的JSONArray作为外层包裹
+            // 创建一个JSONObject对象
+            JSONObject jsonObject = new JSONObject();
+            // 创建一个JSONArray对象,用于存放data数组
             JSONArray dataArray = new JSONArray();
-            // 将你的JSON对象添加到空的JSONArray中
-            dataArray.put(json);
+            // 创建两个JSONObject对象,分别表示data数组中的两个元素
+            JSONObject item1 = new JSONObject();
+            item1.put("ucid", ucid);
+            item1.put("url", url);
+            // 将两个JSONObject对象添加到dataArray中
+            dataArray.add(item1);
+            // 将dataArray添加到jsonObject中
+            jsonObject.put("data", dataArray);
             // 创建连接
             URL urlObj = new URL(sqlurl);
             con = (HttpURLConnection) urlObj.openConnection();
@@ -32,7 +34,7 @@ public class SaveRecord {
 
             // 发送POST请求
             con.setDoOutput(true);
-            byte[] out = dataArray.toString().getBytes(StandardCharsets.UTF_8);
+            byte[] out = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
             con.setFixedLengthStreamingMode(out.length);
             con.getOutputStream().write(out);
             System.out.println(con.getResponseCode());

+ 2 - 2
src/main/java/com/wj/service/impl/UploadFile.java

@@ -39,7 +39,7 @@ public class UploadFile {
                 + "\r\n" + str
                 + "\r\n" + "UCID:" + UCID + "\r\n");
         if (etag != null && hashCrc64ecma != null) {
-            String URL = "https://" + endpoint + UCID + ".wav";
+            String URL = "https://" + endpoint + "/" + UCID + ".wav";
             // 调用数据库接口保存记录
             boolean isUploaded = SaveRecord.saverecord(sqlurl, UCID, URL);
             if (isUploaded) {
@@ -58,7 +58,7 @@ public class UploadFile {
                 + "\r\n" + str
                 + "\r\n" + "UCID:" + UCID + "\r\n");
         if (etag != null && hashCrc64ecma != null) {
-            String URL = "https://" + endpoint + file;
+            String URL = "https://" + endpoint + "/" + file;
             // 调用数据库接口保存记录
             boolean isUploaded = SaveRecord.saverecord(sqlurl, UCID, URL);
             if (isUploaded) {

+ 1 - 1
src/main/java/com/wj/service/impl/XmlProcessor.java

@@ -46,7 +46,7 @@ public class XmlProcessor {
             String switchCallId = getElementValue(doc, "switch_call_id");
             // 获取属性值
             String endTime = getAttributeValue(doc);
-            String fileName = getElementValue(doc, "inum");
+            String fileName = getElementValue(doc, "inum") + ".wav";
 
             OffsetDateTime parsedEndTime = null;
 

+ 57 - 0
src/main/java/com/wj/utils/AudioTransferWavUtils.java

@@ -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);
+    }
+}

+ 24 - 0
src/main/java/com/wj/utils/FileUtils.java

@@ -0,0 +1,24 @@
+package com.wj.utils;
+
+import java.io.File;
+
+public class FileUtils {
+
+    public static void createDirectoryIfNotExists(String directoryPath) {
+        File directory = new File(directoryPath);
+        if (!directory.exists()) {
+            try {
+                boolean created = directory.mkdirs();
+                if (created) {
+                    System.out.println("文件夹已创建: " + directoryPath);
+                } else {
+                    System.out.println("无法创建文件夹: " + directoryPath);
+                }
+            } catch (SecurityException e) {
+                System.out.println("没有权限创建文件夹: " + directoryPath);
+                e.printStackTrace();
+            }
+        }
+    }
+}
+

+ 1 - 1
src/main/resources/application.properties

@@ -15,7 +15,7 @@ threadtimeout = 60
 # 想用文件路径file可以设置成False
 setkey=True
 # 设置文件存储地址
-base.dir=D:/Desktop/calls
+base.dir=D:/Desktop/2024-05
 # 设置自定义日期范围的开始和结束日期,格式为 yyyy-MM-dd
 upload.startDate=2020-05-01
 upload.endDate=2024-05-31