<canvas id="canvas" style="width:100%;height:600px;"></canvas>
<audio id="audio" :src="audioSrc" autoplay controls controlslist="nodownload" @play="onplay" @pause='onPause' @ended="overAudio"></audio>
let config = {
URL: '',
timeout: 3000,
headers: {'content-Type': '', 'token': ''}
responseType: 'arraybuffer',
params: ''
}
axios.get('', config).then((data) => {
const blob = new Blob([data])
audioSrc = window.URL.createObjectURL(blob)
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audio = new AudioContext();
let analyser = audio.createAnalyser();
analyser.fftSize = 256; //设置傅里叶系数
let source = audio.createBufferSource();
audio.decodeAudioData(data, function (buffer) {
// 将解码后得到的值赋给buffer
source.buffer = buffer;
// 音频==》分析器==》扬声器
source.connect(analyser);
analyser.connect(audio.destination);
});
this.$nextTick(() => {
const canvas = document.getElementById("canvas");
const cxt = canvas.getContext("2d");
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
const lineWidth = 4;
const gap = 6;
const maxNum = Math.round(WIDTH / (lineWidth + gap));
cxt.strokeStyle = "red";
cxt.lineCap = "round";
cxt.lineWidth = lineWidth;
const that = this;
onplay()
function render() {
cxt.clearRect(0, 0, WIDTH, HEIGHT); //清空画布
//that.analyser.frequencyBinCount是fftSize的一半
const dataArray = new Uint8Array(that.analyser.frequencyBinCount);
that.analyser.getByteFrequencyData(dataArray); //获取音频字节流
for (let i = 0; i < maxNum; i++) {
cxt.strokeStyle = "#008b8b";
const value = Math.round((dataArray[i] / 128) * 20);
cxt.beginPath();
cxt.moveTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2);
cxt.lineTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2 - value - 2);
cxt.stroke();
cxt.beginPath();
cxt.moveTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2);
cxt.lineTo(i * (lineWidth + gap) + gap / 2, HEIGHT / 2 + value + 2);
cxt.stroke();
}
//递归调用渲染
window.requestAnimationFrame(render);
}
// requestAnimationFrame()用来渲染动画帧,此时渲染第一帧
window.requestAnimationFrame(render);
})
})
// 开始
function onplay() {
let startTime = that.audio.currentTime;
that.source.start(0, startTime);
}
// 暂停
function onPause () {
}
// 结束
function overAudio () {
}
audio音频可视化
最新推荐文章于 2024-09-01 08:08:01 发布