SpringBoot+Vueでダイナミックな音声再生を実現

SpringBoot+Vue でダイナミックな音声再生を実現。効果を実感:

  • ページのブロードキャスト ボイス ボタンをクリックしてバックグラウンド インターフェイスを呼び出し、バイナリ バイトを取得します[]
  • フロントエンドは返されたデータを取得し、ブラウザ コントロールの AudioContext を呼び出してオーディオ ストリームをデコードし、再生を実現します。

1. バックグラウンド インターフェイスが byte[] を返す

1. コントローラーにインターフェースを追加し、byte[] を返す

  • セットを生成します="アプリケーション/オクテット ストリーム"
  • 戻り値の型を設定する 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);
}

この例では、Alibaba Cloud tts インターフェイスを呼び出して、テキストを音声に変換します。

2. configureMessageConverters にパーサーを追加するByteArrayHttpMessageConverter

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

2. 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
      });
}

おすすめ

転載: blog.csdn.net/wlddhj/article/details/130370981