ブラウザ上で録音できるツールをflask + recorder.js + p5.js on TypeScript で作る
Web Audio API のラッパーである recorder.js を用いて簡易レコーダーを作成します。ブラウザ版 Processing である p5.js を ts で書いて UI 実装します。
フィールドレコーディング:スタジオ外での自然音や環境音の録音 自然音や環境音を手軽に集めたい,そしてそれを PC へ送りリアルタイムに処理したい,といったニッチな要望に応えるものを作った感じです
完成イメージ
イメージといってもスクリーンショットなんでこういう感じで動きます。

(たぶん)ササっと環境構築して動かせるので興味ある方は是非。
recorderjsでフロント側で音声録音する
GitHub: https://github.com/mattdiamond/Recorderjs
まずデモはこちらSimple Recorder.js demo
Web Audio API のラッパーみたいな感じでしょうか。AudioNode のインスタンスを渡せば簡単に録音スタート・ストップ・保存ができる,という優れモノ。
以下のような感じで録音開始の関数定義ができるので,任意のイベントで呼べば良い。
1let recorder: Recorder; 2 3const startUserMedia = (stream: MediaStream) => { 4 audio_context = new AudioContext(); 5 let input: AudioNode = audio_context.createMediaStreamSource(stream); 6 recorder = new Recorder(input); 7}; 8 9const startRecording = () => { 10 recorder && recorder.record(); 11};
で,このRecorder.exportWAV()メソッド一発で wav の Blob オブジェクトが手に入るので,ソレを ajax で POST してあげれば良い。
1recorder && 2 recorder.exportWAV((blob: Blob) => { 3 let url = URL.createObjectURL(blob); 4 let fd = new FormData(); 5 fd.append("data", blob); 6 $.ajax({ 7 type: "POST", 8 url: "/", 9 data: fd, 10 }).done((data) => { 11 recorder.clear(); 12 }); 13 });
flaskでPOSTされたwavファイルを保存する
flask 側ではこんな感じに書けば良い。
1from flask import Flask, jsonify, request 2 3 4@app.route('/', methods=['POST']) 5def uploaded_wav(): 6 fname = "sounds/" + datetime.now().strftime('%m%d%H%M%S') + ".wav" 7 with open(f"{fname}", "wb") as f: 8 f.write(request.files['data'].read()) 9 print(f"posted sound file: {fname}") 10 return jsonify({"data": fname})
これでsounds/直下に1104235900.wavみたいなファイルがどんどん溜まっていく。
保存されたファイルのパスをoscで送る
個人的にこのアプリケーションをパフォーマンスで使用したいので,サウンドファイルが保存されたタイミングで osc にメッセージを飛ばしてみる。コレで例えばサーバとなっているローカルの PC で Max/MSP や Max for Live を用いたリアルタイムでのサウンドファイル読み込みがラクになる(と信じている)
pythonoscというパッケージを用いる。(pip install python-oscで入る)
python-osc PyPI: https://pypi.org/project/python-osc/
1from pythonosc import dispatcher, osc_message_builder, osc_server, udp_client 2 3 4address = "127.0.0.1" 5port = 5050 6client = udp_client.UDPClient(address, port) 7 8 9def send_osc(msg): 10 msg_obj = osc_message_builder.OscMessageBuilder(address=address) 11 msg_obj.add_arg(msg) 12 client.send(msg_obj.build())
これで良い。あとは上述のuploaded_wav()内でsend_osc(fname)してあげれば,ファイルパスがメッセージとして届く。Max なら[udpreceive 5050]しておけば open&sfplay~して再生できる。
p5.js
p5js.org: https://p5js.org/
DOM がいじれる Processing という感じで,Canvas 要素に描画するので CSS で複雑なアニメーションを描いているとかしなくても,canvas が動くブラウザなら良いしこっちのがラクかもしれないです。また,Web Editor(https://editor.p5js.org/) というものがあり,環境構築ナシで挙動が試せるので非常にとっかりやすいと思います。
TypeScript を導入するなら,まず以下のリポジトリを使うべきです(めっちゃラクだった)
かつ,以下のエントリを参考にしました
- TypeScript+webpack で Processing(p5.js)の環境を構築する - Qiita
- CreativeCoding 用に P5.js が TypeScript で書ける環境をつくった。 - Qiita
あとは,ササっと書いていくだけです。例として UI の録音ボタンの部分のクラスをおいておきます…
1class Button { 2 private w: number; 3 private h: number; 4 private centerX: number; 5 private centerY: number; 6 private radius: number; 7 private isRecording: boolean; 8 private rectCircleRatio: number; 9 private progress: number; // 0 ~ 300 value (about 5s) 10 11 constructor(w: number, h: number, size: number) { 12 this.w = w; 13 this.h = h; 14 this.centerX = w / 2; 15 this.centerY = h / 2; 16 this.radius = size; 17 this.isRecording = false; 18 this.rectCircleRatio = size / 2; 19 this.progress = 0; 20 } 21 22 isTouched(x: number, y: number) { 23 if ((x - this.centerX) ** 2 + (y - this.centerY) ** 2 < this.radius ** 2) { 24 return true; 25 } 26 return false; 27 } 28 29 switchRecording() { 30 this.isRecording = !this.isRecording; 31 console.log(`switched to recording: ${this.isRecording}`); 32 if (this.isRecording) { 33 startRecording(); 34 } else { 35 this.progress = 0; 36 stopRecording(); 37 } 38 } 39 40 draw() { 41 if (this.progress == 300) { 42 this.progress = 0; 43 this.switchRecording(); 44 } 45 if (this.isRecording) { 46 if (this.rectCircleRatio > 5) { 47 clear(); 48 this.rectCircleRatio -= 5; 49 } 50 this.progress++; 51 } else { 52 if (this.rectCircleRatio <= this.radius / 2) { 53 clear(); 54 this.rectCircleRatio += 5; 55 } 56 } 57 drawCircleUI((this.progress * 2 * PI) / 300); 58 noStroke(); 59 fill(mainColor); 60 rect( 61 this.centerX - this.radius / 2, 62 this.centerY - this.radius / 2, 63 this.radius, 64 this.radius, 65 this.rectCircleRatio, 66 ); 67 // text 68 fill(white); 69 textAlign(CENTER, CENTER); 70 textSize(16); 71 if (this.isRecording) { 72 text("STOP", this.centerX, this.centerY); 73 } else { 74 text("REC", this.centerX, this.centerY); 75 } 76 } 77}
リポジトリ
実際に活用できるので気が向いたらどうぞ。osc-webappと同じく,ngrok で https トンネルほって公開してます。(https じゃないと Web Audio API が使えない)