aiaiask.com©

开花即结果 提问即答案

用js写一个可切换多种样式的可视化音频动态炫酷的代码
原始问题:

用js写一个可切换多种样式的可视化音频动态炫酷的代码



音频可视化





<button onclick='changeStyle(3)' >Style 3</button><br />    

<script type="text/javascript">                //定义全局变量        var audio, context, analyser, visualizer, styleIndex=1;;      //初始化函数,用来获取音频文件和绘图环境     function init(){       audio = document.getElementById('audio');       context = new AudioContext();       analyser = context.createAnalyser();       visualizer = document.getElementById('visualizer');        //将analyser与source连接起来        var source = context.createMediaElementSource(audio);        source.connect(analyser);        analyser.connect(context.destination);         //定义一个Uint8Array来保存声波数据         var dataArray = new Uint8Array(analyser.frequencyBinCount);          //在动画循环中不断地读取并绘制声波数据           renderFrame();      };         //定义renderFrame函数,用来循环读取并绘制声波数据      function renderFrame(){          requestAnimationFrame(renderFrame);           //读取当前的声波数据          analyser.getByteFrequencyData(dataArray);            //计算当前的能量值          var energy=calculateEnergy();              drawSpectrum(energy);      };         //定义drawSpectrum函数,用来根据能量值加以处理后写入Canvas中      function drawSpectrum (energy){           var ctx=visualizer.getContext('2d');            ctx.clearRect (0, 0 , visualizer .width , visualizer .height );             switch (styleIndex)             {                  case 1 :                    drawStyle1 (ctx , energy );                    break ;                  case 2 :                    drawStyle2 (ctx , energy );                    break ;                  case 3 :                    drawStyle3 (ctx , energy );                    break ;             };      };         //定义calculateEnergy函数,用来计算当前的能量值      function calculateEnergy (){           var sum=0 ;            for (var i=0 ;i<dataArray .length ;i++)                 sum+=dataArray[i];                         return sum/dataArray .length /256 *100 ;               };                /* 各样式对应的处理方式 */                /* 样式1 */                function drawStyle1 (ctx , e ){                     ctx .fillRect ( 0 , 0 , e*10+50 , 300 );               };                /* 样式2 */                function drawStyle2 (ctx , e ){                     for (var i=e*10+50 ;i-- ;)                      ctx .fillRect ((300 -i)*Math .random ()*10 +20 , i*Math .random ()*5+20, 10, 10)              };                 /* 样式3 */                 function drawStyle3 (ctx , e ){                     for (var i=(e+50)*5 ;)                      ctx .fillRect ((300 -i)*Math .random ()*10 +20, i*Math .random ()*5+20, 10, 10)              };               /* 切换样式函数 */               function changeStyle (_index){                   styleIndex=_index % 3 + 1 ;               };     </script> </body></html>
用js写一个可切换多种样式的可视化音频动态炫酷的代码
https://www.aiaiask.com/ask/4325.html
AI / 模型Siliconflow
时间 / DATEMarch 29, 2023, 10:10 AM
语言zh-CN
IP / 区域江苏 淮安