H5의 Canvas를 사용하여 음악 원형 스펙트로그램을 그리는 방법

php中世界最好的语言
풀어 주다: 2018-03-12 15:11:47
원래의
4713명이 탐색했습니다.

이번에는 H5의 Canvas를 사용하여 음악 링 스펙트로그램을 그리는 방법을 보여 드리겠습니다. H5Canvas에서 음악 링 스펙트로그램을 그릴 때 주의사항은 무엇인가요?

스테이션 B에 있는 우리 친구들 중 다수가 AE가 만든 영상 음악 플레이어를 사용하여 음악을 재생하는 영상을 본 적이 있을 텐데, 매우 멋지고 신나는 것 같습니다.

H5의 Canvas를 사용하여 음악 원형 스펙트로그램을 그리는 방법

그래서 오늘은 Canvas를 사용하여 간단한 링 스펙트로그램을 만들어 보겠습니다.

그럼~ ヾ(・・Ω・)ノ 시작해볼까요!

1. 먼저 정적 효과

정적 효과

정적 효과를 그리는 방법은 매우 간단합니다. 한 점과 특정 각도에서 선을 그린 다음 시작하는 선을 덮는 원을 그리면 됩니다.

<canvas id="wrap" height="800" width="800"></canvas><script>
    var wrap = document.getElementById("wrap");    var cxt = wrap.getContext("2d");
    (function drawSpectrum() {
        cxt.clearRect(0, 0, wrap.width, wrap.height);        //画线条
        for (var i = 0; i < 360; i++) {            var value = 8;
            cxt.beginPath();
            cxt.lineWidth = 2;
            cxt.moveTo(300, 300);             //R * cos (PI/180*一次旋转的角度数) ,-R * sin (PI/180*一次旋转的角度数)
            cxt.lineTo(Math.cos((i * 1) / 180 * Math.PI) * (200 + value) + 300, (- Math.sin((i * 1) / 180 * Math.PI) * (200 + value) + 300));
            cxt.stroke();
        }        //画一个小圆,将线条覆盖
        cxt.beginPath();
        cxt.lineWidth = 1;
        cxt.arc(300, 300, 200, 0, 2 * Math.PI, false); 
        cxt.fillStyle = "#fff";
        cxt.stroke();
        cxt.fill(); 
    })();</script>
로그인 후 복사

2. AudioAPI를 호출하여 음악의 스펙트로그램 그리기

음악의 스펙트로그램 그리기

첫 번째 단계가 완료된 후 두 번째 단계는 AudioAPI를 호출하여 를 얻는 방법으로 매우 간단합니다. 오디오변경.

주의! ! ! 최신 크롬 브라우저는 http 서버에서 실행해야 할 수도 있습니다~

음악의 스펙트로그램을 그리는 방법은 기사를 참조하세요(분석기 노드 사용)

<input type="button" onclick="audio.play()" value="播放" /><input type="button" onclick="audio.pause()" value="暂停" /><canvas id="wrap" height="800" width="800"></canvas><script> 
    var wrap = document.getElementById("wrap");    var cxt = wrap.getContext("2d");    //获取API
    var AudioContext = AudioContext || webkitAudioContext;    var context = new AudioContext;    //加载媒体
    var audio = new Audio("demo.mp3");    //创建节点
    var source = context.createMediaElementSource(audio);    var analyser = context.createAnalyser();    //连接:source → analyser → destination
    source.connect(analyser);
    analyser.connect(context.destination);    //创建数据
    var output = new Uint8Array(360);
    (function drawSpectrum() {
        analyser.getByteFrequencyData(output);//获取频域数据
        cxt.clearRect(0, 0, wrap.width, wrap.height);        //画线条
        for (var i = 0; i < 360; i++) {            var value = output[i] / 8;//<===获取数据
            cxt.beginPath();
            cxt.lineWidth = 2;
            cxt.moveTo(300, 300);            //R * cos (PI/180*一次旋转的角度数) ,-R * sin (PI/180*一次旋转的角度数)
            cxt.lineTo(Math.cos((i * 1) / 180 * Math.PI) * (200 + value) + 300, (- Math.sin((i * 1) / 180 * Math.PI) * (200 + value) + 300));
            cxt.stroke();
        }        //画一个小圆,将线条覆盖
        cxt.beginPath();
        cxt.lineWidth = 1;
        cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
        cxt.fillStyle = "#fff";
        cxt.stroke();
        cxt.fill();        //请求下一帧
        requestAnimationFrame(drawSpectrum);
    })();</script>
로그인 후 복사

3. 링 좌우 동시 표시

인턴십 2단계 후 , 실제로는 절반 이상이 완성되었습니다. 그러나 주의 깊은 친구들은 링의 가장 오른쪽 끝점에 있는 선들 사이에 많은 차이가 있다는 것을 알게 될 것입니다.

이를 처리하는 방법에는 여러 가지가 있습니다. 우리는 이를 처리하는 간단한 방법 중 하나를 사용하여 대칭으로 표시하도록 합니다.

<input type="button" onclick="audio.play()" value="播放" /><input type="button" onclick="audio.pause()" value="暂停" /><canvas id="wrap" height="550" width="800"></canvas><script> 
    var wrap = document.getElementById("wrap");    var cxt = wrap.getContext("2d");    //获取API
    var AudioContext = AudioContext || webkitAudioContext;    var context = new AudioContext;    //加载媒体
    var audio = new Audio("demo.mp3");    //创建节点
    var source = context.createMediaElementSource(audio);    var analyser = context.createAnalyser();    //连接:source → analyser → destination
    source.connect(analyser);
    analyser.connect(context.destination);    //创建数据
    var output = new Uint8Array(361);
    (function drawSpectrum() {
        analyser.getByteFrequencyData(output);//获取频域数据
        cxt.clearRect(0, 0, wrap.width, wrap.height);        //画线条
        for (var i = 0; i < output.length; i++) {            var value = output[i] / 10;            //绘制左半边
            cxt.beginPath();
            cxt.lineWidth = 1;
            cxt.moveTo(300, 300);
            cxt.lineTo(Math.cos((i *0.5 + 90) / 180 * Math.PI) * (200 + value) + 300, (- Math.sin((i *0.5 + 90) / 180 * Math.PI) * (200 + value) + 300));
            cxt.stroke();            //绘制右半边
            cxt.beginPath();
            cxt.lineWidth = 1;
            cxt.moveTo(300, 300);
            cxt.lineTo( (Math.sin((i *0.5) / 180 * Math.PI) * (200 + value) + 300),-Math.cos((i *0.5) / 180 * Math.PI) * (200 + value) + 300);
            cxt.stroke();
        }        //画一个小圆,将线条覆盖
        cxt.beginPath();
        cxt.lineWidth = 1;
        cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
        cxt.fillStyle = "#fff";
        cxt.stroke();
        cxt.fill();        //请求下一帧
        requestAnimationFrame(drawSpectrum);
    })();</script>
로그인 후 복사

4. 웨이브폼 그래프 추가

마지막으로 원 안에 웨이브폼 그래프를 추가해 보겠습니다

음악의 웨이브폼 그래프를 그리는 방법은 글을 참고하시면 됩니다(Analyzer 노드 이용)

예제

<input type="button" onclick="audio.play()" value="播放" /><input type="button" onclick="audio.pause()" value="暂停" /><canvas id="wrap" height="550" width="800"></canvas><script> 
    var wrap = document.getElementById("wrap");    var cxt = wrap.getContext("2d");    //获取API
    var AudioContext = AudioContext || webkitAudioContext;    var context = new AudioContext;    //加载媒体
    var audio = new Audio("demo.mp3");    //创建节点
    var source = context.createMediaElementSource(audio);    var analyser = context.createAnalyser();    //连接:source → analyser → destination
    source.connect(analyser);
    analyser.connect(context.destination);    //创建数据
    var output = new Uint8Array(361);    //计算出采样频率44100所需的缓冲区长度
    var length = analyser.frequencyBinCount * 44100 / context.sampleRate | 0;    //创建数据 
    var output2 = new Uint8Array(length);
    (function drawSpectrum() {
        analyser.getByteFrequencyData(output);//获取频域数据
        cxt.clearRect(0, 0, wrap.width, wrap.height);        //画线条
        for (var i = 0; i < output.length; i++) {            var value = output[i] / 10;            //绘制左半边
            cxt.beginPath();
            cxt.lineWidth = 1;
            cxt.moveTo(300, 300);
            cxt.lineTo(Math.cos((i * 0.5 + 90) / 180 * Math.PI) * (200 + value) + 300, (- Math.sin((i * 0.5 + 90) / 180 * Math.PI) * (200 + value) + 300));
            cxt.stroke();            //绘制右半边
            cxt.beginPath();
            cxt.lineWidth = 1;
            cxt.moveTo(300, 300);
            cxt.lineTo((Math.sin((i * 0.5) / 180 * Math.PI) * (200 + value) + 300), -Math.cos((i * 0.5) / 180 * Math.PI) * (200 + value) + 300);
            cxt.stroke();
        }        //画一个小圆,将线条覆盖
        cxt.beginPath();
        cxt.lineWidth = 1;
        cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
        cxt.fillStyle = "#fff";
        cxt.stroke();
        cxt.fill();        //将缓冲区的数据绘制到Canvas上 
        analyser.getByteTimeDomainData(output2);        var height = 100, width = 400;
        cxt.beginPath();        for (var i = 0; i < width; i++) {
            cxt.lineTo(i + 100, 300 - (height / 2 * (output2[output2.length * i / width | 0] / 256 - 0.5)));
        }
        cxt.stroke();        //请求下一帧
        requestAnimationFrame(drawSpectrum);
    })();</script>
로그인 후 복사

믿겠습니다. 당신은 이 기사의 사례를 읽었습니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

관련 읽기:

캔버스를 사용하여 유용한 그래피티 드로잉 보드를 만드는 방법

s-xlsx를 사용하여 Excel 파일을 가져오고 내보내는 방법(2부)

위 내용은 H5의 Canvas를 사용하여 음악 원형 스펙트로그램을 그리는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!