基于SpringBoot和Vue的动态语音播放怎么实现
作者:SoftHope
时间:2023-05-11
来源:正软商城
浏览:3
一、后台接口返回byte[]1、在controller中添加接口,返回byte[]设置produces=“application/octet-stream”设置返回类型ResponseEntity@PostMapping(value="/v/voice",produces="application/octet-stream")publicResponseEntityvoice(@RequestBodyJSONObjectparam,HttpServletResponseresponse)throwsIOE
本文目录
一、后台接口返回byte[]
1、在controller中添加接口,返回byte[]
设置 produces = “application/octet-stream”
设置 返回类型 ResponseEntity
@PostMapping(value = "/v/voice", produces = "application/octet-stream") public ResponseEntityvoice(@RequestBody JSONObject param, HttpServletResponse response) throws IOException { String text = param.getString("text"); // 以下代码调用阿里云接口,把文字转语音 byte[] voice = SpeechRestfulUtil.text2voice(text); // 返回音频byte[] return ResponseEntity.ok().body(voice); }
本例是调用阿里云tts接口,把文字转语音
2、在configureMessageConverters中添加解析器
ByteArrayHttpMessageConverter
@Override public void configureMessageConverters(List> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper()); converters.add(jackson2HttpMessageConverter); converters.add(new ByteArrayHttpMessageConverter()); }
二、Vue前端调用接口播放语音
使用axios调用后端接口,设置 responseType=blob
1)得到浏览器播放控件 audioContext
2)使用FileReader读取得到的byte[]
3)FileReader绑定load事件,读取byte[]完成后播放语音
function doVoice(){
axios({
method:'post',
url:req.voice,
responseType:'blob',
data:{text:data.info} // 需要播放的文本
}).then(function (response) {
console.log(response);
if(response.status===200){
// 1)得到浏览器播放控件 audioContext
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let reader = new FileReader();
reader.onload = function(evt) {
if (evt.target.readyState === FileReader.DONE) {
// 3)FileReader绑定load事件,读取byte[]完成后播放语音
audioContext.decodeAudioData(evt.target.result,
function(buffer) {
// 解码成pcm流
let audioBufferSouceNode = audioContext.createBufferSource();
audioBufferSouceNode.buffer = buffer;
audioBufferSouceNode.connect(audioContext.destination);
audioBufferSouceNode.start(0);
}, function(e) {
console.log(e);
});
}
};
// 2)使用FileReader读取得到的byte[]
reader.readAsArrayBuffer(response.data);
}
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
作者最新文章
动漫共和国官网入口在哪
2026-11-04 12:06
office安装工具箱 常用功能介绍
2026-11-02 16:29
悟空浏览器怎么彻底清理浏览器配置文件
2026-11-02 10:28
BOBO浏览器安卓手机版下载与横屏设置教程
2026-10-30 17:48
上一篇:
怎么用命令行清除Redis缓存
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















