LoginSignup
10
6

More than 3 years have passed since last update.

p5.jsで音楽を可視化する

Posted at

はじめに

今回は、音楽に合わせて変化するアニメーションの作り方について解説していく。今回は『デザインとプログラミング』の講義で使用しているp5.jsを使う。
ちなみに、実装物はこのリンクからご覧頂けます。

プログラムの概要

今回実装したプログラムは以下のようなものである。

1. 音の周波数に対応した棒グラフが変化する

2.1番低い周波数の棒グラフが赤、高くなるほど黄色くなる

3. 音量と再生速度を変化させられる

実装

本プログラムでp5.jsで高速フーリエ変換を行うコードは以下のものである。
高速フーリエ変換の具体的な解説はこちらの解説を参考にして欲しい。


let spectrum = fft.analyze();// FFTの結果を取得
  noStroke();

for (let i = 0; i< spectrum.length; i++){

   fill(255, 255*i/spectrum.length, 0); // 色を指定する

   let x = map(i, 0, spectrum.length, 0, width); // 周波数を計算する

   let h = -height + map(spectrum[i], 0, 255, height, 0); // 振幅を計算する

   rect(x+50, height, width / spectrum.length, h ) // 棒グラフ1つ分を作成する

  } 

ちなみに、コード全体はこのようになる。

let playButton; // 再生ボタン
let volumeSlider; // 音量のスライド
let speedSlider; // 再生速度のスライド

function setup(){ // 全体の設定

  createCanvas(windowWidth,windowHeight);

    playButton = createButton("Play"); // 再生ボタンの定義
    playButton.size(100, 50);         // 再生ボタンの大きさを設定
    playButton.position(100, 20);    // 再生ボタンの位置を設定
    playButton.style('background-color', color(30));// 再生ボタンの位置を設定
    playButton.style('color', color(200));   // 再生ボタンの背景の色を設定
    playButton.mousePressed(play_stop);// 再生ボタンを押した時の関数を設定

    volumeSlider = createSlider(0, width, width/2);// 音量のバーを設定
    volumeSlider.position(250, 50);// 音量のバーの位置を設定

    speedSlider = createSlider(0, width, width/2);// 再生速度のバーを設定
    speedSlider.position(400, 50);// 再生速度のバーの位置を設定

  fft = new p5.FFT();// FFTを設定

}

function draw(){ \\ 描画する関数

  background(50);

  let spectrum = fft.analyze();
  noStroke();

  for (let i = 0; i< spectrum.length; i++){
        fill(255, 255*i/spectrum.length, 0);
    let x = map(i, 0, spectrum.length, 0, width);
    let h = -height + map(spectrum[i], 0, 255, height, 0);
    rect(x+50, height, width / spectrum.length, h )
  }

    let volume = map(volumeSlider.value(), 0, width, 0, 0.5); // 音量の変数を定義
    volume = constrain(volume, 0.001, 0.1); // 音量を0.001~0.1に圧縮
  sound.amp(volume); // 音量を決定

    let speed = map(speedSlider.value(), 0.1, width, 0, 2); // 再生速度の変数を定義
    speed = constrain(speed, 0.5, 2); // 再生速度を0.5~2に圧縮
    sound.rate(speed); // 再生速度を決定

}


function preload(){  //  音源を定義する

  sound = loadSound('13647.mp3'); // 音声データを読み込む
  //  予めOpen Processingにアップロードする
}

function play_stop() { // 音源を再生・停止する

  if (sound.isPlaying()) { // 音源が再生している時
    sound.pause(); //  音源を停止する
        playButton.html("Pause"); // ボタンを停止に変える
  } 

    else { // 音源が停止している時
    sound.loop(); // 音源を再生する
        playButton.html("Play"); //  ボタンを再生に変える
  }

}   

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6