LLaSM / static /js /waveview.js
TabShu's picture
docs: upload demo page
441af09
raw history blame
No virus
2.77 kB
/*
录音
https://github.com/xiangyuecn/Recorder
src: extensions/waveview.js
*/
!function(){var e=function(e){return new t(e)},g="WaveView",t=function(e){var t=this,a={scale:2,speed:9,phase:21.8,fps:20,keep:!0,lineWidth:3,linear1:[0,"rgba(150,96,238,1)",.2,"rgba(170,79,249,1)",1,"rgba(53,199,253,1)"],linear2:[0,"rgba(209,130,255,0.6)",1,"rgba(53,199,255,0.6)"],linearBg:[0,"rgba(255,255,255,0.2)",1,"rgba(54,197,252,0.2)"]};for(var i in e)a[i]=e[i];t.set=e=a;var r=e.elem;r&&("string"==typeof r?r=document.querySelector(r):r.length&&(r=r[0])),r&&(e.width=r.offsetWidth,e.height=r.offsetHeight);var n=e.scale,h=e.width*n,o=e.height*n;if(!h||!o)throw new Error(g+"无宽高");var l=t.elem=document.createElement("div"),s=["","transform-origin:0 0;","transform:scale("+1/n+");"];l.innerHTML='<div style="width:'+e.width+"px;height:"+e.height+'px;overflow:hidden"><div style="width:'+h+"px;height:"+o+"px;"+s.join("-webkit-")+s.join("-ms-")+s.join("-moz-")+s.join("")+'"><canvas/></div></div>';var c=t.canvas=l.querySelector("canvas"),d=t.ctx=c.getContext("2d");c.width=h,c.height=o,t.linear1=t.genLinear(d,h,e.linear1),t.linear2=t.genLinear(d,h,e.linear2),t.linearBg=t.genLinear(d,o,e.linearBg,!0),r&&(r.innerHTML="",r.appendChild(l)),t._phase=0};t.prototype=e.prototype={genLinear:function(e,t,a,i){for(var r=e.createLinearGradient(0,0,i?0:t,i?t:0),n=0;n<a.length;)r.addColorStop(a[n++],a[n++]);return r},genPath:function(e,t,a){for(var i=[],r=this.set,n=r.scale,h=r.width*n,o=r.height*n/2,l=0;l<h;l+=n){var s=(1+Math.cos(Math.PI+l/h*2*Math.PI))/2*o*t*Math.sin(2*Math.PI*(l/h)*e+a)+o;i.push(s)}return i},input:function(e,t,a){var i=this;i.sampleRate=a,i.pcmData=e,i.pcmPos=0,i.inputTime=Date.now(),i.schedule()},schedule:function(){var e=this,t=e.set,a=Math.floor(1e3/t.fps);e.timer||(e.timer=setInterval(function(){e.schedule()},a));var i=Date.now();if(!(i-(e.drawTime||0)<a)){e.drawTime=i;for(var r=e.sampleRate/t.fps,n=e.pcmData,h=e.pcmPos,o=Math.max(0,Math.min(r,n.length-h)),l=0,s=0;s<o;s++,h++)l+=Math.abs(n[h]);e.pcmPos=h,!o&&t.keep||e.draw(Recorder.PowerLevel(l,o)),!o&&1300<i-e.inputTime&&(clearInterval(e.timer),e.timer=0)}},draw:function(e){var t=this,a=t.set,i=t.ctx,r=a.scale,n=a.width*r,h=a.height*r,o=a.speed/a.fps,l=t._phase-=o,s=l+o*a.phase,c=e/100,d=t.genPath(2,c,l),g=t.genPath(1.8,c,s);i.clearRect(0,0,n,h),i.beginPath();for(var p=0,f=0;f<n;p++,f+=r)0==f?i.moveTo(f,d[p]):i.lineTo(f,d[p]);p--;for(f=n-1;0<=f;p--,f-=r)i.lineTo(f,g[p]);i.closePath(),i.fillStyle=t.linearBg,i.fill(),t.drawPath(g,t.linear2),t.drawPath(d,t.linear1)},drawPath:function(e,t){var a=this.set,i=this.ctx,r=a.scale,n=a.width*r;i.beginPath();for(var h=0,o=0;o<n;h++,o+=r)0==o?i.moveTo(o,e[h]):i.lineTo(o,e[h]);i.lineWidth=a.lineWidth*r,i.strokeStyle=t,i.stroke()}},Recorder[g]=e}();