Open1

p5jsとsonic piを使ってライブコーディングをする

からくれ178からくれ178

https://in-thread.sonic-pi.net/t/sonic-pi-x-p5js/7413
基本的には上記に書かれた操作をすれば動く。

$ git clone https://github.com/genekogan/p5js-osc
$ cd p5js-osc/
$ npm install

pythonを立ち上げてサーバーを立てる。

python -m http.server

次にnodeで p5js-oscを立ち上げる。

node bridge.js


この画面が開くのでサンプル(p5-basic)をクリック。

p5-basicフォルダのsketch.jsのコードを修正していく。

var ellipseAlpha = 100 // initialized variable for alpha
var  ellipseSize = 50; // initialized variable for size

function setup() {
	createCanvas(500, 500);
	setupOsc(3333, 4560); // OSC ports. you'll need 3333 in your Sonic Pi code
}

function draw() {
	background(0, 0, 255);
	fill(0, 255, 0, ellipseAlpha); // fill using alpha variable
	ellipse(200, 200, ellipseSize, ellipseSize); // ellipses function using size variable

}

// this function controls the incoming OSC messages
function receiveOsc(address, value) {
	console.log("received OSC: " + address + ", " + value);

// This conditional statement looks for "cutoff" message and assigns its value to alpha variable
	if (address == '/cutoff') { 
		ellipseAlpha= value[0];
	}
// This conditional statement looks for "amp" message and assigns its value to size variable
if (address == '/amp') {
		ellipseSize = value[0];
	}
}

// This function is for sending OSC messages
// This is not relevant for receiving OSC messages
function sendOsc(address, value) {
	socket.emit('message', [address].concat(value));
}

function setupOsc(oscPortIn, oscPortOut) {
	var socket = io.connect('http://127.0.0.1:8081', { port: 8081, rememberTransport: false });
	socket.on('connect', function() {
		socket.emit('config', {
			server: { port: oscPortIn,  host: '127.0.0.1'},
			client: { port: oscPortOut, host: '127.0.0.1'}
		});
	});
	socket.on('message', function(msg) {
		if (msg[0] == '#bundle') {
			for (var i=2; i<msg.length; i++) {
				receiveOsc(msg[i][0], msg[i].splice(1));
			}
		} else {
			receiveOsc(msg[0], msg.splice(1));
		}
	});
}

sonic piに以下のように記載する。

# Welcome to Sonic Pi
use_osc "localhost", 3333
live_loop :oscTest do
  n1 = rrand(1, 100)
  osc "/cutoff" , n1
  play 60, cutoff: n1
  sleep 1
end

これでcutoffという文字列に入った変数をp5js上で取り出せるようになった。