今天學習到用canvas來寫 HTML5音頻可視化頻譜跳動代碼 將代碼在此作一總結:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML5音頻可視化頻譜跳動代碼</title> <style> * { margin: 0; padding: 0; } #canvas { display: block; background: linear-gradient(135deg, rgb(142, 13, 133) 0%, rgb(230, 132, 110) 100%); } </style> </head> <body> <audio id="myaudio" src="./mp3.mp3"></audio> <canvas id="canvas"></canvas> <script> window.onload = function () { var oAudio = document.getElementById('myaudio'); window.onclick = function () { if (oAudio.paused) { oAudio.play(); } else { oAudio.pause(); } } // 建立音頻上下文對象 var oCtx = new AudioContext(); // 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 = new Uint8Array(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 */ } </script> </body> </html>
其效果圖爲:canvas