2018年7月11日 星期三

Javascript 3D + Audio - 1

整合 P5.Sound + a-frame.io
Ref: cdn p5.js and p5.sound.js
cdn  :   https://cdnjs.com/libraries/p5.js/
Ref: a-frame  https://aframe.io/docs/0.8.0/introduction/
1. p5.js example
1-1
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
1-2 初始化設定
1-2-1 function setup() 環境設定
1-2-2 function draw()  定時重繪畫面
1-3 p5.sound 初始化
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.min.js"></script>
1-3-1 function preload() 載入mp3 file
1-3-2 配合 p5.js setup()與draw() 處理聲音同步
1-4 a-frame 3D 架構
    <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
1-4-1 3D 場景
<body>內建置<a-scene>場景
1-4-2 draw 取得amp與3D屬性同步修改

1-5 範例
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.min.js"></script>
    <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
    <script>
function preload(){
  sound = loadSound('assets/aa1.mp3');
}
function setup() {
  amplitude = new p5.Amplitude();

  // start / stop the sound when canvas is clicked
document.addEventListener("click", function(){
     if (sound.isPlaying() ){
          sound.stop();
        } else {
          sound.play();
        }
    });
}
function draw() {
  var level = amplitude.getLevel();
  var sceneEl = document.querySelector('a-scene');
  var sphere1 = sceneEl.querySelector('#sphere1');
  sphere1.setAttribute('radius', level * 20);
}
    </script>
</head>
<body>

    <a-scene>
      <a-box color="#4CC3D9" position="-1 0.5 -3" rotation="0 45 0"></a-box>
      <a-sphere color="#EF2D5E" id="sphere1" position="0 1.25 -5" radius="1.25"></a-sphere>
      <a-cylinder color="#FFC65D" height="1.5" position="1 0.75 -3" radius="0.5"></a-cylinder>
      <a-plane color="#7BC8A4" height="4" position="0 0 -4" rotation="-90 0 0" width="4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>
</body>
</html>

沒有留言:

張貼留言