HTML5音頻可視化頻譜跳動代碼
*{
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)
//利用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();}