Spring AI(音频转文本、文本转音频)
接上篇:Spring AI(绘图)
1、音频转文本
application.yml新增配置
# 语音转文本 audio: transcription: options: # 模型版本 model: whisper-1
完整配置如下:

spring: application: name: spring-ai ai: openai: # 访问open ai接口的api key api-key: sk-3sfER03LDLG3SDFsdlwe283JSdw023lkrmrHDND32fmREKFD # 访问open ai的接口地址 base-url: https://openai.com/ # ai聊天设置 chat: options: # chatGpt模型版本,32k是参数量,若当前代码中和application配置文件中同时声明,则代码中的配置会覆盖application配置文件中的 model: gpt-4-32k # 温度越高,回答的准确率会下降,温度越低,回答的准确率越好,若当前代码中和application配置文件中同时声明,则代码中的配置会覆盖application配置文件中的 temperature: 0.3F # ai绘图设置 image: options: # 模型版本 model: gpt-4-dalle # 图片质量 quality: hd # 数量 n: 2 # 高度 height: 1920 # 宽度 width: 1080 # 语音转文本 audio: transcription: options: # 模型版本 model: whisper-1
模板模型版本可以debug查询,或者看文档
示例代码如下:

/** * 音频转文本 * @author ithailin */ @RestController @RequestMapping("/ai") public class TranscriptionController { private static final Logger logger = LoggerFactory.getLogger(TranscriptionController.class); @Autowired private OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel; /** * 音频转文本 * public String call(Resource audioResource){} * @return */ @RequestMapping("/transcription") public Object transcription(){ Resource audioFile = new ClassPathResource("test.mp3"); String call = openAiAudioTranscriptionModel.call(audioFile); logger.info("call:{}",call); return call; } }
2、文本转音频

/** * 文本转音频 * @author ithailin */ @RestController @RequestMapping("/AI") public class TTSController { private static final Logger logger = LoggerFactory.getLogger(TTSController.class); @Autowired private OpenAiAudioSpeechModel openAiAudioSpeechModel; /** * 音频转文本 * public String call(Resource audioResource){} * @return */ @RequestMapping("/tts") public Object tts(String msg){ logger.info("msg:{}",msg ); //msg若为空,转换会异常,msg中文、英文都支持 byte[] call = openAiAudioSpeechModel.call(msg); FileUtils.save2File("D:\\SpringAI\\test.mp3",call); return "OK"; } }
FileUtils.java

public class FileUtils { /** * 方法功能:将字节数组写入到新建文件中。 * @return boolean * */ public static boolean save2File(String fname, byte[] msg){ OutputStream fos = null; try{ File file = new File(fname); File parent = file.getParentFile(); boolean bool; if ((!parent.exists()) && (!parent.mkdirs())) { return false; } fos = new FileOutputStream(file); fos.write(msg); fos.flush(); return true; }catch (FileNotFoundException e){ return false; }catch (IOException e){ e.printStackTrace(); return false; } finally{ if (fos != null) { try{ fos.close(); } catch (IOException e) {} } } } }
接下篇:Spring AI(多模态)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?