- base64 转 blob 方法封装如下:
function base64ToBlob(base64, fileType) {
// 第一种:拼接base64
// let typeHeader = 'data:application/' + fileType + ';base64,'; // 定义base64 头部文件类型
// let audioSrc = typeHeader + base64; // 拼接最终的base64
// 第二种:直接传入base64文件
let audioSrc = base64; // 拼接最终的base64
let arr = audioSrc.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转为blob并进行播放。
let bs64 = ' ' //此参数作为一个base64文件的变量
let newBlob = base64ToBlob(bs64,'mp3')
// console.log('newBlob--', newBlob)
var path = window.URL.createObjectURL(newBlob);
var audio = document.createElement('audio');
// console.log(path)
audio.src = path;
audio.controls = true;
audio.volume = '0.2';
audio.play()
document.getElementById('audioId').appendChild(audio)
audio.addEventListener("canplay", () => {
window.URL.revokeObjectURL(audio.src);
});