java:音频转base64

发布于:2025-03-24 ⋅ 阅读:(19) ⋅ 点赞:(0)

话不多说上代码



import com.alibaba.fastjson.JSON;
import com.race.APPControl.RaceAPPControlApplication;


import com.race.APPControl.domain.DeepseekLog;
import com.race.APPControl.service.DeepseekLogService;
import com.race.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.io.*;
import java.util.Base64;
import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RaceAPPControlApplication.class)
@Slf4j
public class TestClass {
    @Resource
    private DeepseekLogService deepseekLogService;



    @Test
    public void appcontrol() throws IOException {
        String audioFilePath = "C:\\Users\\pc\\Desktop\\1\\aa\\bilu\\20250304_090935.m4a"; // 替换为你的音频文件路径
        String outputFilePath = "C:\\Users\\pc\\Desktop\\1\\aa\\rbmp\\generated_sql.txt";
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));

        String base64String = encodeAudioToBase64(audioFilePath);

        if (base64String != null) {
            writer.write(base64String);
            writer.newLine();
            log.info("Base64 encoded audio: " + base64String);
        } else {
            System.out.println("Failed to encode audio to Base64.");
        }
    }

    public static String encodeAudioToBase64(String filePath) {
        File audioFile = new File(filePath);
        if (!audioFile.exists() || !audioFile.isFile()) {
            System.err.println("File does not exist or is not a valid file: " + filePath);
            return null;
        }

        try (FileInputStream fileInputStream = new FileInputStream(audioFile)) {
            // 读取文件的字节数据
            byte[] fileBytes = new byte[(int) audioFile.length()];
            fileInputStream.read(fileBytes);

            // 将字节数据编码为 Base64
            return Base64.getEncoder().encodeToString(fileBytes);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
            return null;
        }
    }

}