温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2023-04-26 11:03:26 来源:亿速云 阅读:94 作者:iii 栏目:开发技术

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

一、后台接口返回byte[]

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

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

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

@PostMapping(value = "/v/voice", produces = "application/octet-stream")
public ResponseEntity<byte[]> voice(@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<HttpMessageConverter<?>> 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
      });
}

到此,相信大家对“基于SpringBoot和Vue的动态语音播放怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI