基于SpringBoot和Vue的动态语音播放怎么实现

其他教程   发布日期:2025年04月18日   浏览次数:175

本篇内容主要讲解“基于SpringBoot和Vue的动态语音播放怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“基于SpringBoot和Vue的动态语音播放怎么实现”吧!

一、后台接口返回byte[]

1、在controller中添加接口,返回byte[]

  • 设置 produces = “application/octet-stream”

  • 设置 返回类型 ResponseEntity<byte[]>

  1. @PostMapping(value = "/v/voice", produces = "application/octet-stream")
  2. public ResponseEntity<byte[]> voice(@RequestBody JSONObject param, HttpServletResponse response) throws IOException {
  3. String text = param.getString("text");
  4. // 以下代码调用阿里云接口,把文字转语音
  5. byte[] voice = SpeechRestfulUtil.text2voice(text);
  6. // 返回音频byte[]
  7. return ResponseEntity.ok().body(voice);
  8. }

本例是调用阿里云tts接口,把文字转语音

2、在configureMessageConverters中添加解析器

  1. ByteArrayHttpMessageConverter
  1. @Override
  2. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  3. MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper());
  4. converters.add(jackson2HttpMessageConverter);
  5. converters.add(new ByteArrayHttpMessageConverter());
  6. }

二、Vue前端调用接口播放语音

使用axios调用后端接口,设置 responseType=blob

1)得到浏览器播放控件 audioContext

2)使用FileReader读取得到的byte[]

3)FileReader绑定load事件,读取byte[]完成后播放语音

  1. function doVoice(){
  2. axios({
  3. method:'post',
  4. url:req.voice,
  5. responseType:'blob',
  6. data:{text:data.info} // 需要播放的文本
  7. }).then(function (response) {
  8. console.log(response);
  9. if(response.status===200){
  10. // 1)得到浏览器播放控件 audioContext
  11. let audioContext = new (window.AudioContext || window.webkitAudioContext)();
  12. let reader = new FileReader();
  13. reader.onload = function(evt) {
  14. if (evt.target.readyState === FileReader.DONE) {
  15. // 3)FileReader绑定load事件,读取byte[]完成后播放语音
  16. audioContext.decodeAudioData(evt.target.result,
  17. function(buffer) {
  18. // 解码成pcm流
  19. let audioBufferSouceNode = audioContext.createBufferSource();
  20. audioBufferSouceNode.buffer = buffer;
  21. audioBufferSouceNode.connect(audioContext.destination);
  22. audioBufferSouceNode.start(0);
  23. }, function(e) {
  24. console.log(e);
  25. });
  26. }
  27. };
  28. // 2)使用FileReader读取得到的byte[]
  29. reader.readAsArrayBuffer(response.data);
  30. }
  31. })
  32. .catch(function (error) {
  33. // handle error
  34. console.log(error);
  35. })
  36. .finally(function () {
  37. // always executed
  38. });
  39. }

以上就是基于SpringBoot和Vue的动态语音播放怎么实现的详细内容,更多关于基于SpringBoot和Vue的动态语音播放怎么实现的资料请关注九品源码其它相关文章!