*{
margin:0;
padding:0;
}
#canvas {
display: block;
background: linear-gradient(135deg, rgb(142, 13, 133) 0%, rgb(230, 132, 110) 100%);
}
window.οnclick=function () {if(oAudio.paused) {
oAudio.play();
}else{
oAudio.pause();
}
}//創建音頻上下文對象
var oCtx = newAudioContext();//console.log(oCtx);//創建媒體源,除了audio本身可以獲取,也可以通過oCtx對象提供的api進行媒體源操作
var audioSrc =oCtx.createMediaElementSource(oAudio);//創建分析機
var analyser =oCtx.createAnalyser();//媒體源與分析機連接
audioSrc.connect(analyser);//輸出的目標:將分析機分析出來的處理結果與目標點(耳機/揚聲器)連接
analyser.connect(oCtx.destination);//效果(實現的具體方法)//繪制音頻圖的條數(fftSize)
/*根據分析音頻的數據去獲取音頻頻次界定音頻圖的高度
放在與音頻頻次等長的8位無符號字節數組
Uint8Array:初始化默認值為1024*/
//利用cancas漸變進行音頻繪制
var ctx = canvas.getContext('2d');
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;var oW =canvas.width;var oH =canvas.height;var color1 = ctx.createLinearGradient(oW / 2, oH / 2 - 30, oW / 2, oH / 2 - 100);var color2 = ctx.createLinearGradient(oW / 2, oH / 2 + 30, oW / 2, oH / 2 + 100);
color1.addColorStop(0, '#000');
color1.addColorStop(.5, '#069');
color1.addColorStop(1, '#f6f');
color2.addColorStop(0, '#000');
color2.addColorStop(.5, '#069');
color2.addColorStop(1, '#f6f');//音頻圖的條數
var count = 150;//緩沖區:進行數據的緩沖處理,轉換成二進制數據
var voiceHeight = newUint8Array(analyser.frequencyBinCount);//console.log(voiceHeight);
function draw() {//將當前的頻率數據復制到傳入的無符號字節數組中,做到實時連接
analyser.getByteFrequencyData(voiceHeight);//console.log(voiceHeight);//自定義獲取數組里邊數據的頻步
var step = Math.round(voiceHeight.length /count);
ctx.clearRect(0, 0, oW, oH);for (var i = 0; i < count; i++) {var audioHeight = voiceHeight[step *i];
ctx.fillStyle= color1; //繪制向上的線條
ctx.fillRect(oW / 2 + (i * 10), oH / 2, 7, -audioHeight);
ctx.fillRect(oW/ 2 - (i * 10), oH / 2, 7, -audioHeight);
ctx.fillStyle= color2; //繪制向下的線條
ctx.fillRect(oW / 2 + (i * 10), oH / 2, 7, audioHeight);
ctx.fillRect(oW/ 2 - (i * 10), oH / 2, 7, audioHeight);
}
window.requestAnimationFrame(draw);
}
draw();/*analyserNode 提供了時時頻率以及時間域的分析信息
允許你獲取實時的數據,并進行音頻可視化
analyserNode接口的fftSize屬性
fftSize:無符號長整型值,用于確定頻域的FFT(快速傅里葉變換)
ffiSize屬性值是從32位到32768范圍內的2的非零冪,默認值是2048*/}