0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MMLの楽譜をM5UnitSynthで流す

0
Last updated at Posted at 2026-03-01

前回は、MML_Playのお力を借りて、ESP32でブザーを使ってMML楽譜で音楽を流しました。

ESP32でMMLを使って懐かしの音楽を再生する

その時には、ブザーを使ったビープ音でしたが、今度はM5UnitSynthのシンセサイザを使って、きれいな音色のメロディーを流します。

MML_Playからフォークして、以下を作成しました。

使い方

以下、サンプルを見ていただければ早いです。

main.cpp
#include <Arduino.h>
#include "MML_Synth.h"

#include <M5UnitSynth.h>

#define SYNTH_DEFAULT_CHANNEL 0

static M5UnitSynth synth;
MML_Synth mml;

// 単音出力関数
void dev_tone(uint8_t pitch, uint16_t vol) {
  synth.setNoteOn(SYNTH_DEFAULT_CHANNEL, pitch, vol / 15 * 127);
}

void dev_instrument(uint8_t value) {
  synth.setInstrument(0, SYNTH_DEFAULT_CHANNEL, value);
}

// 単音出力停止関数
void dev_notone() {
}

// 猫ふんじゃった
const char * mmltext =
  "v1?O6t160v15l16d+c+r8f+rf+rd+c+r8f+rf+rd+c+l8rf+r"
  "f+rl16frfrd+c+r8frfrd+c+r8frfrd+c+l8"
  "rfrfrl16f+rf+rd+c+r8f+rf+rd+c+r8f+r"
  "f+rd+c+l8rf+rf+rl16frfrd+c+r8frfrd+c+r8fr"
  "frd+c+l8rfrfrl16f+rf+rd+c+l8rf+rf+rf+r"
  "f+rf+rf+rl16frfrd+c+l8rfrfrfrfrfrfrl16"
  "f+rf+rd+c+r8f+rf+rd+c+r8f+rf+rd+c+l8r"
  "f+rf+rl16frfrd+c+r8frfrd+c+r8frfrd+c+l8"
  "rfrfrl16f+rf+r8.f+rc+c+d8c+8.frf+?"
  ;
  
// デバッグ出力用
void debug(uint8_t c) {
  Serial.write(c);
}

void setup() {
  Serial.begin(115200);

  synth.begin(&Serial2, UNIT_SYNTH_BAUD, 33, 32);

  mml.init(nullptr, dev_tone, dev_notone, dev_instrument, debug);
  mml.setText(mmltext);
  mml.playBGM();
}

void loop() {
  // put your main code here, to run repeatedly:

  if (mml.isBGMPlay()) {
    // 演奏状態で演奏継続可能なら1音再生
    if (mml.available()) 
      mml.playTick();    
  }
}

Javascriptコード

いつものJavascriptからの実行例です。

main.js
import * as unitsynth from "UnitSynth";

var text = "t120v1?O6t080v15l16d+c+r8f+rf+rd+c+r8f+rf+rd+c+l8rf+r" +
  "f+rl16frfrd+c+r8frfrd+c+r8frfrd+c+l8" +
  "rfrfrl16f+rf+rd+c+r8f+rf+rd+c+r8f+r" +
  "f+rd+c+l8rf+rf+rl16frfrd+c+r8frfrd+c+r8fr" +
  "frd+c+l8rfrfrl16f+rf+rd+c+l8rf+rf+rf+r" +
  "f+rf+rf+rl16frfrd+c+l8rfrfrfrfrfrfrl16" +
  "f+rf+rd+c+r8f+rf+rd+c+r8f+rf+rd+c+l8r" +
  "f+rf+rl16frfrd+c+r8frfrd+c+r8frfrd+c+l8" +
  "rfrfrl16f+rf+r8.f+rc+c+d8c+8.frf+?";

function setup(){
	unitsynth.begin(32, 33, 10);
	unitsynth.play(text, false);
}

楽譜の中に、@番号 を入れるか、unitsynth.setInstrument(番号)を呼び出すことで、いろんな音色を切り替えられます。

(参考) ESP32で動作するJavascript実行環境

ESP32で動作するJavascript実行環境を公開しています。
Javascriptのコードを書き換えるのに、いちいち再コンパイル不要なので、らくちんです。

「電子書籍:M5StackとJavascriptではじめるIoTデバイス制御」

サポートサイト

ぜひ、手に取ってみてください。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?