在处理微信语音中它的音频是amr格式、但是在普通的audio中是不能播放的
在下面有两种方法 js外链接引入/npm引入
。
// 如果是vue项目 则npm引入
npm install benz-amr-recorder
let BenzAMRRecorder = require('benz-amr-recorder'); //引入
this.amr = null;
this.amr = new BenzAMRRecorder(); //创建
this.amr.initWithUrl(data.audios[0].url); //初始化
this.amrTime.duration = data.audios[0].duration / 1000; //音频总时长
this.amr.play() //播放
this.amr.stop() //停止
// 如果是h5中的项目 则引入外链接amr.js
let url="xxxxxxxxx.amr"
let gAudioContext = new AudioContext();
function getAudioContext() {
if (!gAudioContext) {
gAudioContext = new AudioContext();
}
return gAudioContext;
}
//开始播放
window.playAmr = function (url) {
fetchBlob(amrUrl, function (blob) {
playAmrBlob(blob);
});
};
function fetchBlob(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = function () {
callback(this.response);
};
xhr.onerror = function () {
alert('Failed to fetch ' + url);
};
xhr.send();
}
function readBlob(blob, callback) {
const reader = new FileReader();
reader.onload = function (e) {
const data = new Uint8Array(e.target.result);
callback(data);
};
reader.readAsArrayBuffer(blob);
}
function playAmrBlob(blob, callback) {
readBlob(blob, function (data) {
playAmrArray(data);
});
}
function playAmrArray(array) {
const samples = AMR.decode(array);
if (!samples) {
alert('播放失败,请下载后播放!');
return;
}
playPcm(samples);
}
let preCtx = null;
function playPcm(samples) {
if (preCtx !== null) {
stopPlay();
}
const ctx = getAudioContext();
const src = ctx.createBufferSource();
const buffer = ctx.createBuffer(1, samples.length, 8000);
if (buffer.copyToChannel) {
buffer.copyToChannel(samples, 0, 0);
} else {
const channelBuffer = buffer.getChannelData(0);
channelBuffer.set(samples);
}
src.buffer = buffer;
src.connect(ctx.destination);
src.start();
preCtx = src;
}
//停止播放
function stopPlay() {
if (preCtx !== null) {
preCtx.stop();
}
preCtx = null;
}
//调用playAmr() 就可播放音频