点击某图片或者按钮播放音频

接口给我返回的是slk文件,先转base64再转MP3文件。

import http from "../api/http";

//可以把base64转音频文件的
function base64ToBlob(urlData, type) {
  let arr = urlData.split(",");
  let array = arr[0].match(/:(.*?);/);
  let mime = (array && array.length > 1 ? array[1] : type) || type;
  // 去掉url的头,并转化为byte
  let bytes = window.atob(arr[1]);
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  // 生成视图(直接针对内存):8位无符号整数,长度1个字节
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: mime
  });
}

//把base64转mp3格式
export function slkToMp3(url){
  return new Promise((resolve, reject) => {
    http.get("/xkfApi/xkf-api/slk-to-mp3", {url}).then(res => {
      let typeHeader = "data:audio/mpeg;base64,"; // 定义base64 头部文件类型
      let converedBase64 = typeHeader + res; // 拼接最终的base64
      let blob = base64ToBlob(converedBase64, "mp3");
      let src = window.URL.createObjectURL(blob);
      resolve(src)
    }).catch((err) => {
      reject('解码失败')
      console.error(err)
    })
  })
}

 

在需要的地方引入,然后设置个点击事件。

import {slkToMp3} from "@/util/voice.js"
//点击播放语音
	const stop = () =>{
	  if(window.voiceCrl){
	   window.voiceCrl.pause();
	   window.voiceCrl = null;
		}
	}
        //playVoice是点击事件,会传进去一个slk的
        //每次点击先停止上一次的
   const playVoice =  (voice_url) =>{
  	  stop();
  	   slkToMp3(voice_url).then(res => {
  	    window.voiceCrl = new Audio(res);
  		window.voiceCrl.onended = () => {
  		stop();
  		}
  		window.voiceCrl.onerror = () => {
  		 console.error('不支持的音频格式');
  		 stop();
  		  }

		  window.voiceCrl.play();
		})
      }

 

posted @ 2022-08-04 14:41  Private!  阅读(153)  评论(0编辑  收藏  举报