AGENT SKILL

sound-id

暂无简介

License 许可
MIT
最近更新
2026-09-04
Stars
★ 0
Forks
0

02 资源文件 3

03 SKILL.md 正文

SoundID — OpenClaw Skill Documentation

Skill name: sound-id Purpose: Provides microphone access and audio analysis for the SoundID R1 Creation.

The R1 Creations sandbox has no direct microphone API. SoundID delegates all audio capture and optional pre-processing to this OpenClaw skill running on a paired computer. The Creation sends commands via the shared-storage bridge (openclaw:cmd), and this skill writes results back to openclaw:resp.


Commands

Command Params Description
record-start durationSecs, category Start capturing audio; run optional pre-analysis
record-stop (none) Stop early and flush any buffered data

record-start

Captures audio from the system microphone for durationSecs (default 10). When complete it writes an audioDescription string to the response that the Creation feeds into the R1 built-in LLM for final identification. For the birds category the skill may additionally query the MusicBrainz AcousticID API or a local species database before returning.

Params:

{
  "durationSecs": 10,
  "category": "birds"
}

Response written to openclaw:resp:

{
  "status": "done",
  "ts": 1718234567890,
  "data": {
    "audioDescription": "Short melodic phrases with rising cadence, 2–3 note whistles, repeated every 1.5 seconds. Background: light urban ambient. No obvious mechanical noise.",
    "durationCaptured": 10,
    "category": "birds"
  }
}

If the skill cannot access a microphone, it returns audioDescription: "" — the Creation falls back to LLM-only mode using the category hint.

record-stop

Stops any active recording immediately. No response is written; the Creation handles cleanup on its side.


Node.js Implementation

/**
 * sound-id/skill.js — OpenClaw skill for SoundID
 *
 * Requirements:
 *   npm install node-record-lpcm16 wav musicbrainz-api
 *
 * On macOS/Linux: sox must be installed (brew install sox / apt install sox).
 * On Windows: SoX for Windows or use the naudiodon alternative.
 */

const storage  = require("../openclaw-shared-storage");
const recorder = require("node-record-lpcm16");
const fs       = require("fs");
const path     = require("path");
const https    = require("https");
const os       = require("os");

const POLL_MS    = 400;
const CMD_KEY    = "openclaw:cmd";
const RESP_KEY   = "openclaw:resp";
const SKILL_NAME = "sound-id";

// Temporary audio file path
const TMP_WAV = path.join(os.tmpdir(), "soundid-capture.wav");

let activeRecording = null;
let pollTimer = null;

// ── POLL FOR COMMANDS ─────────────────────────────────────────────────────────

function startPolling() {
  pollTimer = setInterval(async () => {
    try {
      const raw  = await storage.get(CMD_KEY);
      if (!raw) return;
      const cmd  = JSON.parse(raw);
      if (cmd.status !== "pending" || cmd.skill !== SKILL_NAME) return;

      // Mark as in-progress so we don't re-execute
      await storage.set(CMD_KEY, JSON.stringify({ ...cmd, status: "processing" }));

      if (cmd.command === "record-start") {
        await handleRecordStart(cmd.params ?? {});
      } else if (cmd.command === "record-stop") {
        handleRecordStop();
      }
    } catch (err) {
      console.error("[sound-id] poll error:", err.message);
    }
  }, POLL_MS);
}

// ── RECORD START ──────────────────────────────────────────────────────────────

async function handleRecordStart({ durationSecs = 10, category = "unknown" }) {
  console.log(`[sound-id] Recording ${durationSecs}s — category: ${category}`);

  // Abort any existing recording
  handleRecordStop();

  try {
    const audioData = await captureAudio(durationSecs);
    const description = await describeAudio(audioData, category);

    await writeResponse({
      audioDescription: description,
      durationCaptured: durationSecs,
      category,
    });
  } catch (err) {
    console.error("[sound-id] recording failed:", err.message);
    // Write empty description — Creation will fall back to LLM-only
    await writeResponse({
      audioDescription: "",
      durationCaptured: 0,
      category,
      error: err.message,
    });
  }
}

function handleRecordStop() {
  if (activeRecording) {
    try { activeRecording.stop(); } catch (_) {}
    activeRecording = null;
    console.log("[sound-id] recording stopped early");
  }
}

// ── AUDIO CAPTURE ─────────────────────────────────────────────────────────────

function captureAudio(durationSecs) {
  return new Promise((resolve, reject) => {
    const chunks = [];

    const rec = recorder.record({
      sampleRate:  16000,
      channels:    1,
      audioType:   "wav",
      recorder:    "sox",   // change to 'arecord' on Linux if sox unavailable
    });

    activeRecording = rec;

    rec.stream().on("data", chunk => chunks.push(chunk));
    rec.stream().on("error", reject);

    setTimeout(() => {
      try { rec.stop(); } catch (_) {}
      activeRecording = null;
      if (chunks.length === 0) {
        reject(new Error("No audio data captured"));
        return;
      }
      resolve(Buffer.concat(chunks));
    }, durationSecs * 1000);
  });
}

// ── AUDIO DESCRIPTION ─────────────────────────────────────────────────────────
//
// This function converts raw audio to a text description the R1 LLM can reason
// about. It uses a tiered approach:
//
//   Tier 1 — birds: query AcousticID / MusicBrainz fingerprint API
//   Tier 2 — all:   basic heuristics from audio statistics (RMS, zero-crossing)
//   Tier 3 — all:   plain category hint (empty description)

async function describeAudio(audioBuffer, category) {
  try {
    if (category === "birds" || category === "instruments") {
      const fingerprint = await getAcousticFingerprint(audioBuffer);
      if (fingerprint) {
        const match = await queryAcousticID(fingerprint);
        if (match) return match;
      }
    }
    return buildHeuristicDescription(audioBuffer, category);
  } catch (_) {
    return buildHeuristicDescription(audioBuffer, category);
  }
}

// Basic RMS + zero-crossing rate heuristic
function buildHeuristicDescription(audioBuffer, category) {
  // Parse 16-bit PCM samples from WAV (skip 44-byte header)
  const headerSize = 44;
  if (audioBuffer.length <= headerSize) return "";

  const samples = [];
  for (let i = headerSize; i < audioBuffer.length - 1; i += 2) {
    samples.push(audioBuffer.readInt16LE(i) / 32768);
  }

  // RMS (loudness)
  const rms = Math.sqrt(samples.reduce((s, x) => s + x * x, 0) / samples.length);

  // Zero-crossing rate (rough pitch indicator)
  let zcr = 0;
  for (let i = 1; i < samples.length; i++) {
    if ((samples[i] >= 0) !== (samples[i - 1] >= 0)) zcr++;
  }
  zcr = zcr / samples.length;

  const dbEstimate = rms > 0 ? Math.round(20 * Math.log10(rms) + 94) : 0;

  const loudness = dbEstimate >= 85 ? "loud (85+ dB)"
    : dbEstimate >= 70 ? "moderate (70–85 dB)"
    : "quiet (below 70 dB)";

  const pitch = zcr > 0.15 ? "high-frequency content dominant"
    : zcr > 0.05 ? "mid-frequency content"
    : "low-frequency rumble";

  const rhythmic = detectRepetition(samples) ? "with a rhythmic repeating pattern" : "non-repetitive";

  return `${loudness} audio sample, ${pitch}, ${rhythmic}. Category hint: ${category}. ` +
    `Estimated sound pressure: ${dbEstimate} dB. Zero-crossing rate: ${zcr.toFixed(3)}.`;
}

// Naive repetition detector: compare first-quarter against second-quarter
function detectRepetition(samples) {
  const q = Math.floor(samples.length / 4);
  if (q < 100) return false;
  let diff = 0;
  for (let i = 0; i < q; i++) {
    diff += Math.abs(samples[i] - samples[q + i]);
  }
  return (diff / q) < 0.15;
}

// ── ACOUSTICID FINGERPRINTING ─────────────────────────────────────────────────
//
// AcousticID is an open audio fingerprinting service. It is best for identifying
// music and known bird call recordings.  Sign up at https://acoustid.org/login
// to get a free API key and set ACOUSTID_KEY in your environment.

async function getAcousticFingerprint(audioBuffer) {
  const { execSync } = require("child_process");
  // Write buffer to temp file for fpcalc
  fs.writeFileSync(TMP_WAV, audioBuffer);
  try {
    const out = execSync(`fpcalc -json "${TMP_WAV}"`, { timeout: 8000 }).toString();
    const parsed = JSON.parse(out);
    return { duration: parsed.duration, fingerprint: parsed.fingerprint };
  } catch (_) {
    return null;
  }
}

function queryAcousticID({ duration, fingerprint }) {
  const key = process.env.ACOUSTID_KEY;
  if (!key) return Promise.resolve(null);

  return new Promise((resolve) => {
    const params = new URLSearchParams({
      client:      key,
      duration:    Math.round(duration),
      fingerprint: fingerprint,
      meta:        "recordings+releases",
    });

    const req = https.get(
      `https://api.acoustid.org/v2/lookup?${params}`,
      res => {
        let body = "";
        res.on("data", d => (body += d));
        res.on("end", () => {
          try {
            const json = JSON.parse(body);
            const result = json.results?.[0];
            if (!result || result.score < 0.7) { resolve(null); return; }
            const rec = result.recordings?.[0];
            if (!rec) { resolve(null); return; }
            const title  = rec.title ?? "Unknown";
            const artist = rec.artists?.[0]?.name ?? "Unknown artist";
            resolve(`AcousticID match: "${title}" by ${artist}. Score: ${Math.round(result.score * 100)}%.`);
          } catch (_) {
            resolve(null);
          }
        });
      }
    );
    req.on("error", () => resolve(null));
    req.setTimeout(6000, () => { req.destroy(); resolve(null); });
  });
}

// ── WRITE RESPONSE ────────────────────────────────────────────────────────────

async function writeResponse(data) {
  const payload = {
    status: "done",
    ts:     Date.now(),
    data,
  };
  await storage.set(RESP_KEY, JSON.stringify(payload));
  console.log("[sound-id] response written:", JSON.stringify(data).slice(0, 120));
}

// ── SHARED STORAGE STUB ───────────────────────────────────────────────────────
//
// Replace with your actual OpenClaw shared-storage implementation.
// The real implementation writes to/reads from the same key-value store that
// the R1 Creation accesses via window.creationStorage.plain.

// openclaw-shared-storage.js (minimal example — adapt to your setup):
//
// const store = {};
// module.exports = {
//   get: async (k)    => store[k] ?? null,
//   set: async (k, v) => { store[k] = v; },
// };

// ── ENTRY POINT ───────────────────────────────────────────────────────────────

console.log("[sound-id] OpenClaw skill starting — polling for commands");
startPolling();

process.on("SIGINT",  () => { handleRecordStop(); clearInterval(pollTimer); process.exit(0); });
process.on("SIGTERM", () => { handleRecordStop(); clearInterval(pollTimer); process.exit(0); });

Setup

  1. Install Node dependencies:

    npm install node-record-lpcm16 musicbrainz-api
    
  2. Install SoX for audio capture:

    • macOS: brew install sox
    • Ubuntu/Debian: sudo apt install sox
    • Windows: download SoX and add to PATH
  3. (Optional) Install fpcalc (Chromaprint) for AcousticID fingerprinting:

    • macOS: brew install chromaprint
    • Ubuntu: sudo apt install libchromaprint-tools
  4. (Optional) Set ACOUSTID_KEY environment variable with your free AcousticID API key from https://acoustid.org/login

  5. Run the skill:

    node skill.js
    

Architecture notes

Why text descriptions instead of audio file transfer? The OpenClaw bridge uses shared key-value storage (max ~64 KB per value). A raw 10-second WAV at 16 kHz mono is ~320 KB — too large. Instead, the skill extracts a compact text description (RMS, pitch indicators, AcousticID match if any) and sends that. The R1 LLM does the final identification reasoning from the description.

Bird Focus Mode When category === "birds" the skill returns after each recording and the Creation automatically triggers the next record-start command 2 seconds later, creating a continuous scan loop. The loop runs until the user ends Bird Watch via PTT or long-press PTT.

Graceful offline degradation If this skill is not running, the Creation falls back to LLM-only mode with an empty audioDescription. The LLM uses the selected category as a hint and produces a realistic example identification at capped confidence (≤ 45%). The user sees a toast notification: "OpenClaw unavailable — LLM only".


LED color reference

LED color State
Blue #378ADD Recording — actively capturing audio
Amber #EF9F27 Analyzing — LLM processing
Green #639922 Identified — high confidence (75%+)
Amber #EF9F27 Identified — medium confidence (45–74%)
Red #E24B4A Identified — low confidence / unidentified
Teal #1D9E75 Bird Focus Mode active
Off Idle / ready

04 同仓库更多 Skills

ajohnsonnow
ajohnsonnow/r1-warren

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.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

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).

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

voice-novel

Local machine skill for VoiceNovel — handles story export to disk.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

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.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

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.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

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.

★ 0