drum-machine
暂无简介
- License 许可
- MIT
- 最近更新
- 2026-09-04
- Stars
- ★ 0
- Forks
- 0
02 资源文件 3
- 资产文件card.jpg25.6 KB
- 资产文件icon.png9.8 KB
- 参考文档index.html51.2 KB
03 SKILL.md 正文
DrumMachine — OpenClaw Skill & Setup Guide
Skill ID: drum-machine
Creation: drum-machine/index.html
Purpose: Real-time MIDI output for the R1 DrumMachine step sequencer and live play mode.
What This Skill Does
The DrumMachine creation communicates with your local machine via the OpenClaw storage-poll bridge. This skill (a Node.js process on your host) handles:
- Real-time MIDI hit output — converts R1 hit events into MIDI notes played through your DAW or software synth, with sub-10 ms latency.
- Drum kit switching — sends GM program-change messages when you switch kits.
- Pattern export — saves any pattern to a Standard MIDI File (
.mid) in~/DrumMachine/on your machine. - Initialization handshake — opens the MIDI port when the creation boots.
Beat generation (the "Beat Generator" feature) runs entirely through the R1's own
LLM via PluginMessageHandler — no local AI setup required.
Prerequisites
Node.js >= 18
npm install midi @tonejs/midi
Platform notes for the midi package:
| OS | Extra steps |
|---|---|
| Windows | Requires build tools: npm install --global windows-build-tools then npm install midi |
| macOS | No extra steps — CoreMIDI is built in |
| Linux | sudo apt install libasound2-dev then npm install midi |
Virtual MIDI Port Setup
The skill sends MIDI to a port named DrumMachine. You need to create it before
running the skill.
Windows — loopMIDI:
- Download loopMIDI and install it.
- Open loopMIDI, click
+, name the portDrumMachine. - The port persists across reboots.
macOS — IAC Driver:
- Open Audio MIDI Setup (
/Applications/Utilities/). - Open MIDI Studio (Window menu), double-click IAC Driver.
- Check Device is online, add a port named
DrumMachine.
Linux — virtual MIDI:
sudo modprobe snd-virmidi
# Port appears as "Virtual Raw MIDI" — route via aconnect or JACK
DAW Setup (Receive MIDI on Channel 10)
All drum hits are sent on MIDI Channel 10 (General MIDI percussion channel). Kick, Snare, Hi-Hat, and Perc map to standard GM note numbers:
| Instrument | GM Note |
|---|---|
| Kick | 36 (C2) |
| Snare | 38 (D2) |
| Hi-Hat closed | 42 (F#2) |
| Hi-Hat open | 46 (A#2) |
| Perc | 46 (A#2, or 47 depending on kit) |
| Rimshot (live tilt) | 37 (C#2) |
Ableton Live: Add a MIDI track → set MIDI From to DrumMachine / Channel 10 →
drop a Drum Rack on it.
FL Studio: Options → MIDI Settings → Enable DrumMachine input → assign to
a channel with FPC or a drum sampler.
GarageBand: Preferences → MIDI → Enable DrumMachine → create a Software
Instrument track using Drum Kit Designer.
Logic Pro: Preferences → MIDI → Inputs → enable DrumMachine → create a
Software Instrument track set to receive on Channel 10.
Any DAW with General MIDI: Route the DrumMachine port to any GM-compatible
instrument on Channel 10.
OpenClaw Command Reference
Commands arrive via shared storage key openclaw:cmd with skill = "drum-machine".
The skill writes responses to openclaw:resp.
init
Sent once when the creation boots.
{ "bpm": 120, "notes": [36, 38, 42, 46] }
Opens the MIDI port. Returns:
{ "ok": true, "port": "DrumMachine" }
hit
Fire a single drum note immediately. Fire-and-forget — no response written, minimising round-trip latency.
{
"note": 36,
"velocity": 90,
"row": 0,
"rowName": "KICK",
"live": false
}
Live hits (live: true) use velocity 115 for extra presence.
Special notes sent by the creation:
note 37— rimshot (tilt-right in live mode)note 46— open hi-hat (scroll-down in live mode)note 42— closed hi-hat (scroll-up in live mode)
save-midi
Export the current 16-step pattern as a Standard MIDI File.
{
"pattern": [[0,1,...], [0,1,...], [0,1,...], [0,1,...]],
"patternIdx": 0,
"bpm": 120,
"steps": 16,
"notes": [36, 38, 42, 46],
"rowNames": ["KICK", "SNRE", "HH", "PERC"]
}
Output: ~/DrumMachine/pattern-{N}-{bpm}bpm-{timestamp}.mid
Response:
{ "ok": true, "file": "/Users/you/DrumMachine/pattern-1-120bpm-2026-06-14.mid" }
Full Node.js Implementation
Save as drum-machine-skill.js and run with node drum-machine-skill.js.
#!/usr/bin/env node
"use strict";
const midi = require("midi");
const { Midi } = require("@tonejs/midi");
const fs = require("fs");
const path = require("path");
const os = require("os");
// ── Config ──────────────────────────────────────────────────────────────────
const POLL_MS = 200;
const PORT_NAME = "DrumMachine";
const OUTPUT_DIR = path.join(os.homedir(), "DrumMachine");
const STORAGE_DIR = process.env.R1_STORAGE_PATH
|| path.join(os.homedir(), ".config", "RabbitR1", "storage");
const CMD_FILE = path.join(STORAGE_DIR, "openclaw_cmd.json");
const RESP_FILE = path.join(STORAGE_DIR, "openclaw_resp.json");
// ── Storage bridge ──────────────────────────────────────────────────────────
function readCmd() {
try { return JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); }
catch (_) { return null; }
}
function writeResp(data) {
fs.writeFileSync(RESP_FILE, JSON.stringify({ status: "done", ts: Date.now(), data }), "utf8");
}
// ── MIDI output ─────────────────────────────────────────────────────────────
const output = new midi.Output();
let midiPort = -1;
function openMIDI() {
const count = output.getPortCount();
for (let i = 0; i < count; i++) {
const name = output.getPortName(i);
if (name.includes(PORT_NAME) || name.includes("IAC") || name.includes("Microsoft GS")) {
midiPort = i;
break;
}
}
if (midiPort < 0 && count > 0) midiPort = 0;
if (midiPort >= 0) {
output.openPort(midiPort);
console.log(`MIDI: opened "${output.getPortName(midiPort)}"`);
} else {
console.warn("MIDI: no ports found. Create a virtual MIDI port named DrumMachine.");
}
}
function sendNoteOn(note, velocity) {
if (midiPort < 0) return;
output.sendMessage([0x99, note & 0x7F, velocity & 0x7F]); // ch10 note-on
setTimeout(() => output.sendMessage([0x89, note & 0x7F, 0]), 80); // note-off
}
// ── MIDI file export ─────────────────────────────────────────────────────────
function saveMidi({ pattern, patternIdx, bpm, steps, notes, rowNames }) {
if (!fs.existsSync(OUTPUT_DIR)) fs.mkdirSync(OUTPUT_DIR, { recursive: true });
const midiFile = new Midi();
midiFile.header.setTempo(bpm);
const track = midiFile.addTrack();
const PPQ = midiFile.header.ppq;
const step16 = PPQ / 4; // 16th-note duration in ticks
for (let r = 0; r < pattern.length; r++) {
const note = notes?.[r] ?? (36 + r);
for (let s = 0; s < steps; s++) {
if (pattern[r][s]) {
track.addNote({
midi: note,
time: (s * step16) / PPQ,
duration: (step16 * 0.8) / PPQ,
velocity: 0.7,
});
}
}
}
const stamp = new Date().toISOString().slice(0, 10);
const file = path.join(OUTPUT_DIR, `pattern-${patternIdx + 1}-${bpm}bpm-${stamp}.mid`);
fs.writeFileSync(file, Buffer.from(midiFile.toArray()));
console.log(`Saved: ${file}`);
return file;
}
// ── Main poll loop ───────────────────────────────────────────────────────────
let lastTs = 0;
async function poll() {
const cmd = readCmd();
if (!cmd || cmd.ts === lastTs || cmd.skill !== "drum-machine" || cmd.status !== "pending") return;
lastTs = cmd.ts;
console.log(`CMD: ${cmd.command}`);
try {
switch (cmd.command) {
case "init":
writeResp({ ok: true, port: midiPort >= 0 ? output.getPortName(midiPort) : "none" });
break;
case "hit":
sendNoteOn(cmd.params.note ?? 36, cmd.params.velocity ?? 90);
// fire-and-forget: no writeResp for hit — keeps latency low
break;
case "save-midi":
writeResp({ ok: true, file: saveMidi(cmd.params) });
break;
default:
console.warn("Unknown command:", cmd.command);
}
} catch (err) {
console.error("Handler error:", err);
writeResp({ error: err.message });
}
}
// ── Entry point ──────────────────────────────────────────────────────────────
openMIDI();
console.log(`DrumMachine skill running (polling every ${POLL_MS}ms)`);
console.log(`Storage: ${STORAGE_DIR}`);
console.log(`Output: ${OUTPUT_DIR}`);
setInterval(poll, POLL_MS);
process.on("exit", () => { try { output.closePort(); } catch (_) { /* best-effort */ } });
process.on("SIGINT", () => { output.closePort(); process.exit(0); });
process.on("SIGTERM", () => { output.closePort(); process.exit(0); });
Setup Steps
# 1. Install dependencies
cd e:\VS_Studio\rabbit-r1-skillz\drum-machine
npm init -y
npm install midi @tonejs/midi
# 2. Set your R1 storage path (if not using the default)
export R1_STORAGE_PATH=/path/to/RabbitR1/storage # macOS/Linux
set R1_STORAGE_PATH=C:\Users\you\AppData\RabbitR1\storage # Windows
# 3. Run the skill
node drum-machine-skill.js
Open the DrumMachine creation on your R1. The skill receives an init command
and opens the MIDI port automatically.
R1 Controls Reference
Sequencer Mode (SEQ)
| Input | Action |
|---|---|
| Scroll ↑ / ↓ | Move edit cursor left / right across the 16 steps |
| Scroll past step 0 or step 15 | Open pattern slot selector |
| PTT (single tap) | Toggle the focused step on/off |
| Long-press PTT | Cycle active row: Kick → Snare → Hi-Hat → Perc → Kick |
| Long-press PTT (release) | Start / stop playback |
| Tap BPM display | Enter BPM mode |
| Tap SEQ mode tag | Open Beat Generator |
| Tap ▶/■ indicator | Start / stop playback |
| Touch any cell | Toggle that cell; move cursor there |
BPM Mode
| Input | Action |
|---|---|
| Scroll ↑ | Increase BPM by 5 (max 200) |
| Scroll ↓ | Decrease BPM by 5 (min 60) |
| PTT | Confirm and return to SEQ |
Pattern Slot Selector
Reached by scrolling past the first or last step column.
| Input | Action |
|---|---|
| Scroll ↑ / ↓ | Highlight previous / next slot |
| PTT | Load highlighted slot |
Live Play Mode
Entered by double-tapping the SEQ tag in the header.
| Input | Action |
|---|---|
| PTT (tap) | Kick drum — fires immediately |
| Scroll ↑ | Closed hi-hat (MIDI note 42) |
| Scroll ↓ | Open hi-hat (MIDI note 46) |
| Tilt R1 right (accel X > 0.4) | Snare hit (MIDI note 38) |
| Long-press PTT | Exit live mode → back to SEQ |
Beat Generator
Opened by tapping the SEQ mode tag.
| Input | Action |
|---|---|
| Hold PTT | Start voice recording — speak a genre or mood |
| Release PTT | Send to R1 LLM → generates 16-step pattern |
| PTT (when idle/done) | Close overlay |
Example prompts: "trap beat" · "jazz swing" · "bossa nova" · "lo-fi hip hop" ·
"techno" · "industrial" · "reggae"
LED Color Key
| Color | Meaning |
|---|---|
| Red | Kick drum hit |
| Amber | Snare / rimshot hit |
| Blue | Hi-hat hit / live mode active |
| Green | Perc hit / sequencer playing |
| Teal | Beat generator active |
| Off | Stopped / idle |
Pattern File Format
Patterns are stored in R1 creation storage under key dm2:patterns — an
8 × 4 × 16 array of 0 or 1 values:
dm2:patterns[slot][row][step]
slot: 0–7 (8 pattern slots)
row: 0=Kick, 1=Snare, 2=Hi-Hat, 3=Perc
step: 0–15 (16 steps = one bar of 16th notes)
Settings (BPM, active slot) are stored under dm2:settings:
{ "bpm": 120, "curSlot": 0 }
Both keys persist across sessions. Slots 0 and 1 ship with built-in presets (808 and Trap) if no saved patterns are found.
Latency Notes
Real-time hit commands are fire-and-forget (no writeResp) to keep MIDI
latency as low as possible. The Node.js poll loop runs every 200 ms; actual hit
delivery depends on the OS MIDI stack (typically 1–5 ms after the poll fires).
The R1 sequencer uses setTimeout-based scheduling. At 120 BPM each 16th note
is 125 ms; R1 JS timer accuracy is ±5 ms — acceptable for live performance.
For tighter timing, reduce POLL_MS to 100 in the skill script.
04 同仓库更多 Skills
whisper-quiz
WhisperQuiz — voice-answered trivia game for Rabbit R1. Generates questions via the R1's built-in LLM, captures spoken answers via STT, and evaluates correctness with flexible LLM-based matching.
walk-cast
Walking podcast production skill. Receives raw audio metadata and transcript from the R1, removes long pauses, applies noise reduction and normalization, generates AI chapter titles and episode metadata via LLM, and uploads the final episode to your configured podcast RSS host (Spotify for Podcasters / Anchor, Podbean, Buzzsprout, RSS.com, or any FTP-accessible feed).
voice-novel
Local machine skill for VoiceNovel — handles story export to disk.
voice-guide
Environment description and navigation assistant for blind and low-vision users. Analyzes camera frames via a vision LLM, reads visible text, identifies scene categories (people/vehicles/food/hazards/exits), performs 360° scans, retrieves GPS position, and sends emergency SMS alerts — all via audio feedback with zero screen dependency.
voice-draft
Voice-driven document drafting for the Rabbit R1. Dictate stream-of-consciousness speech; the R1 formats it into Email, Blog Post, Report, Proposal, Meeting Notes, Creative Writing, Code Comments, Cover Letter, or Tweet Thread — then saves the result to a configured folder on your local machine via OpenClaw.
voice-commit
Hands-free git and CI workflow voice controller for the Rabbit R1. Speak git/CI commands and hear results — commit, push, status, PR management, test runs, and deploy, all voice-driven via OpenClaw.