package com.guwan.util; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.guwan.config.GlobalValue; import io.minio.MinioClient; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import java.io.InputStream; @Component public class ToTextExample2 { private static MinioClient minioClient; private static GlobalValue globalValue; private static WebClient webClient; public ToTextExample2(MinioClient minioClient, GlobalValue globalValue) { ToTextExample2.minioClient = minioClient; ToTextExample2.globalValue = globalValue; // 初始化 WebClient ToTextExample2.webClient = WebClient.builder() .baseUrl(globalValue.getTransitionApi()) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .build(); } public static String voiceToText(String fileUrl) { try { // 从 MinIO 获取文件 InputStream inputStream = minioClient.getObject(globalValue.getMinioBucketName(), fileUrl); ByteArrayResource fileResource = FileUtil.createByteArrayResource(IOUtils.toByteArray(inputStream), fileUrl); // 设置请求体 MultiValueMap body = new LinkedMultiValueMap<>(); body.add("file", fileResource); body.add("model", globalValue.getModel()); // 发送请求并处理响应 String response = webClient.post() .uri("") // 这里假设是 POST 请求到基础 URL .body(BodyInserters.fromMultipartData(body)) .retrieve() .bodyToMono(String.class) .block(); // 同步调用,若需要异步处理,可以去掉 block() // 解析响应 JSON JSONObject result = JSONUtil.parseObj(response); if (result.containsKey("text")) { String text = result.get("text").toString(); System.out.println(text); return text; } else { System.out.println("1111"); } } catch (Exception e) { e.printStackTrace(); // 输出异常信息 System.out.println("2222"); } return "识别发生错误!"; } }