开始录音
// 开始录音
startRecorder() {
let that = this;
recorder.start().then(
() => {
this.disnext = true;
// 绑定事件-打印的是当前录音数据
recorder.onprogress = function (params) {
that.duration = params.duration.toFixed(3);
};
// this.duration = recorder.duration;
this.drawRecord(); //绘制波浪图
setTimeout(function () {
document.getElementById("instructions").style.backgroundColor =
"green";
}, 300); //三秒之后变色
},
(error) => {
// 出错了
console.log(`${error.name} : ${error.message}`);
}
);
},
结束录音
// 结束录音
stopRecorder() {
this.disnext = false;
this.duration = recorder.duration.toFixed(3);
setTimeout(function () {
document.getElementById("instructions").style.backgroundColor = "red";
}, 300); //三秒之后变色
console.log(recorder.getWAVBlob(), "结束录音");
//获取 WAV 数据,在录音结束后使用 -使用该方法会默认调用 stop() 方法。
const Blob = recorder.getWAVBlob();
//创建一个新的 URL 对象
this.url = URL.createObjectURL(Blob);
// console.log(this.url, "地址");
// recorder.downloadWAV();
},
实现波形图
// 波浪图配置
startCanvas() {
//录音波浪
this.oCanvas = document.getElementById("canvas");
this.ctx = this.oCanvas.getContext("2d");
},
// 录音 音波图
drawRecord() {
// 用requestAnimationFrame稳定60fps绘制
this.drawRecordId = requestAnimationFrame(this.drawRecord);
// 实时获取音频大小数据
let dataArray = recorder.getRecordAnalyseData(),
bufferLength = dataArray.length;
// 填充背景色
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(0, 0, this.oCanvas.width, this.oCanvas.height);
// 设定波形绘制颜色
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = "#409EFF";
this.ctx.beginPath();
var sliceWidth = (this.oCanvas.width * 1.0) / bufferLength, // 一个点占多少位置,共有bufferLength个点要绘制
x = 0; // 绘制点的x轴位置
for (var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = (v * this.oCanvas.height) / 2;
if (i === 0) {
// 第一个点
this.ctx.moveTo(x, y);
} else {
// 剩余的点
this.ctx.lineTo(x, y);
}
// 依次平移,绘制所有点
x += sliceWidth;
}
this.ctx.lineTo(this.oCanvas.width, this.oCanvas.height / 2);
this.ctx.stroke();
},