AudioContext+canvas实现音频可视化

1.创建AudioContext对象

AudioContext() 构造方法创建了一个新的 AudioContext 对象 它代表了一个由音频模块链接而成的音频处理图, 每一个模块由 AudioNode 表示.

let AudioContext = window.AudioContext || window.webkitAudioContext;
let audioContext = new AudioContext();      //实例化AudioContext对象
复制代码

2.创建AnalyserNode节点

let analyser;

analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
复制代码

3.链接节点

 let audioSrc = audioContext.createMediaElementSource(audio); //从audio中获取声音源文件
 audioSrc.connect(analyser);
 analyser.connect(audioContext.destination);
复制代码

4.AnalyserNode数据解析

 let dataArray = new Uint8Array(analyser.frequencyBinCount);
 analyser.getByteFrequencyData(dataArray);
复制代码

5.requestAnimationFrame的使用

要使动画动起来,我们需要不断重绘Canvas标签里的内容,requestAnimationFrame 可以帮你以60fps的帧率绘制动画。

function render() {
    requestAnimationFrame(render);
	//...
}
requestAnimationFrame(render);
复制代码

6.浏览器兼容性:

浏览器 Chrome Firefox IE Opera Safari
支持版本 10.0 25.0 不支持 15.0 6.0

示例代码

js

let AudioContext = window.AudioContext || window.webkitAudioContext;
let audioContext = new AudioContext();
let analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
analyser = audioContext.createAnalyser();

let audio = document.getElementById('audio');
let audioSrc = audioContext.createMediaElementSource(audio);
audioSrc.connect(analyser);
analyser.connect(audioContext.destination);
let canvas = document.getElementById('canvas');

let ctx = canvas.getContext("2d");
ctx.lineWidth = 2;
let grd = ctx.createLinearGradient(0, 0, 600, 0);
grd.addColorStop(0, "#00d0ff");
grd.addColorStop(1, "#eee");

let grd2 = ctx.createLinearGradient(0, 0, 600, 0);
grd2.addColorStop(0, "#fff");
grd2.addColorStop(1, "#e720ee");
let het=0;

var globalID;
function render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let dataArray = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(dataArray);
    ctx.beginPath();
    for (let i = 0; i < 200; i++) {
        let value = dataArray[6*i];
        ctx.fillStyle = grd;
        ctx.fillRect(i * 5, 300, 2, -value + 1);
        ctx.fillRect(i * 5, 280-value, 2, het);
        ctx.fillStyle = grd2;
        ctx.fillRect(i * 5, 300, 2, value + 1);
        ctx.fillRect(i * 5, 320+value, 2, het);
    }
    globalID=requestAnimationFrame(render);
};
globalID=requestAnimationFrame(render);


var fileChange = document.getElementById('fileChooser');
	fileChange.onchange = fileChange=(e)=>{
   if( e.target.files[0]){
	let playfile= URL.createObjectURL( e.target.files[0]);
	audio.src=playfile;
	let musicName = e.target.files[0].name.split('.')[0];
	audio.play();
	}
};
	
复制代码

html



    
        "utf-8" />
        
    
    
    
        
        "canvas" width="800" height="600" >
            Your browser does not support Canvas tag.
        
        "fileChooser" type="file" />
    
	

复制代码

示例:liazm.com/#/audio

转载于:https://juejin.im/post/5bffa17ef265da612e285b66

你可能感兴趣的:(AudioContext+canvas实现音频可视化)