{"id":26690263,"url":"https://github.com/roelvangils/shamon","last_synced_at":"2026-04-25T01:39:01.376Z","repository":{"id":283834181,"uuid":"953044132","full_name":"roelvangils/shamon","owner":"roelvangils","description":"This is a little CLI tool based on Vibra that continuously monitors what music is playing and writes everything to a local SQLite database.","archived":false,"fork":false,"pushed_at":"2025-12-27T13:45:31.000Z","size":86,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-12-29T05:44:48.329Z","etag":null,"topics":["cli","macos","music","shazam"],"latest_commit_sha":null,"homepage":"","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/roelvangils.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-22T12:49:06.000Z","updated_at":"2025-12-27T13:45:34.000Z","dependencies_parsed_at":"2025-03-22T14:20:02.615Z","dependency_job_id":"64bd2089-ab64-4a23-9454-02c36dcb1cd7","html_url":"https://github.com/roelvangils/shamon","commit_stats":null,"previous_names":["roelvangils/shamon"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/roelvangils/shamon","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roelvangils%2Fshamon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roelvangils%2Fshamon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roelvangils%2Fshamon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roelvangils%2Fshamon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/roelvangils","download_url":"https://codeload.github.com/roelvangils/shamon/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roelvangils%2Fshamon/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32247508,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-24T13:21:15.438Z","status":"ssl_error","status_checked_at":"2026-04-24T13:21:15.005Z","response_time":64,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","macos","music","shazam"],"created_at":"2025-03-26T15:26:59.729Z","updated_at":"2026-04-25T01:39:01.338Z","avatar_url":"https://github.com/roelvangils.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Shamon - Music Recognition Monitor\n\nA lightweight CLI tool that continuously monitors and identifies music playing on your computer using Vibra for audio fingerprinting and the Shazam API. Shamon is smarter than running Shazam manually — it normalizes audio for better recognition, intelligently avoids duplicate detections, minimizes API calls, and automatically handles device failures.\n\n## Why Shamon?\n\n| Feature | Shazam App | Shamon |\n|---------|------------|--------|\n| Recognizes quiet audio | ❌ | ✅ Audio normalized to -3dB before recognition |\n| Avoids duplicate entries | ❌ | ✅ Intelligent title matching with time window |\n| Runs continuously | ❌ | ✅ Background monitoring with auto-recovery |\n| Handles device failures | ❌ | ✅ Automatic fallback to next available mic |\n| Minimal API usage | ❌ | ✅ Skips silence, increases interval for same song |\n| Local history | ❌ | ✅ SQLite database with web interface |\n\n## Features\n\n### Intelligent Audio Processing\n- **Audio normalization** — Boosts quiet recordings to -3dB before sending to Shazam, recognizing music that would otherwise be missed\n- **Smart silence detection** — Skips API calls when no audio is detected (threshold: 0.001 RMS)\n- **Single recording, dual use** — Same audio sample used for level detection and recognition (no wasted recordings)\n\n### Smart Song Matching\n- **Title-based matching** — Compares first 3 words of song titles (case-insensitive)\n- **Time window deduplication** — Same song within 60 seconds is considered a repeat\n- **Handles artist variations** — \"You Got The Love\" by \"Candi Staton\" and \"The Source \u0026 Candi Staton\" are correctly matched\n\n### Minimal API Footprint\n- **Adaptive intervals** — Increases wait time when the same song keeps playing\n- **Network check caching** — Caches connectivity status for 30 seconds\n- **Skip on silence** — No API calls when audio level is below threshold\n\n### Reliable Device Handling\n- **Automatic device switching** — Switches to next device after 3 consecutive zero-audio readings\n- **Mic-first fallback** — Prioritizes devices with \"mic\" in the name when searching for alternatives\n- **Preferred device list** — Configure your preferred devices in order of priority\n\n### Additional Features\n- 📊 SQLite database storage for recognition history\n- 🌐 Web server with JSON API and cyberpunk-styled HTML interface\n- 🎨 Colored terminal output with real-time status\n- ⚙️ Configurable via `~/.shamonrc` file\n- 🐛 Debug mode with detailed logging\n- 📱 JSON output mode for integration with other tools\n- 💻 Background/headless operation with screen support\n\n## Installation\n\n### Prerequisites\n\nFirst, install [Vibra](https://github.com/BayernMuller/vibra) on your system. Follow the instructions in the Vibra repository.\n\n### System Dependencies\n\nInstall required system dependencies:\n\n**macOS:**\n```bash\nbrew install sox jq sqlite3 bc screen\n```\n\n**Linux (Ubuntu/Debian):**\n```bash\nsudo apt-get install sox jq sqlite3 bc screen\n```\n\n### Python Dependencies (for web server)\n\nIf you want to use the web interface:\n\n```bash\npip install -r requirements.txt\n```\n\nOr install manually:\n```bash\npip install fastapi uvicorn\n```\n\n## Usage\n\n### Basic Commands\n\n```bash\n./shamon.sh                        # Interactive mode with device selection\n./shamon.sh --json                 # JSON output mode\n./shamon.sh --debug                # Debug mode with logging\n./shamon.sh --auto-input           # Auto-select input device from preferred list\n./shamon.sh --headless             # Run in background without console output\n./shamon.sh --version              # Show version information\n./shamon.sh --help                 # Show help message\n```\n\n### Combined Flags\n\nYou can combine multiple flags:\n\n```bash\n./shamon.sh --auto-input --headless       # Auto-select device and run in background\n./shamon.sh --auto-input --debug          # Auto-select with debug logging\n./shamon.sh --json --auto-input           # JSON output with auto-selected device\n```\n\n## Configuration\n\nCreate a `~/.shamonrc` file to customize Shamon's behavior:\n\n```bash\n# Preferred audio input devices (in order of preference)\nPREFERRED_DEVICES=(\n    \"My Webcam\"\n    \"Built-in Microphone\"\n)\n\n# Audio detection threshold (default: 0.001, very sensitive due to normalization)\nAUDIO_THRESHOLD=0.001\n\n# Base interval between checks (in seconds)\nBASE_INTERVAL=15\n\n# Maximum interval between checks\nMAX_INTERVAL=120\n\n# Enable debug mode by default\nDEBUG=true\n```\n\n## Headless Mode\n\nWhen using the `--headless` flag, the script will:\n- Start in the background and immediately return control to the terminal\n- Display the process ID (PID) for managing the background process\n- Log all output to `~/.music_monitor.log`\n- Continue monitoring music until stopped\n\n### macOS Audio Access in Background\n\nOn macOS, background processes may lose access to CoreAudio devices. Shamon handles this automatically with several options:\n\n#### Option 1: Screen Session (Recommended)\n\nIf `screen` is installed, Shamon will automatically use it to maintain audio access:\n\n```bash\n# Install screen if needed\nbrew install screen\n\n# Start with screen support\n./shamon.sh --auto-input --headless\n```\n\nOutput:\n```\n📻 Music Monitor started in background mode (screen session)\nScreen session: shamon_12345\nProcess ID: 12345\nLog file: ~/.music_monitor.log\nTo view: screen -r shamon_12345\nTo stop: screen -S shamon_12345 -X quit\n```\n\n#### Option 2: Background Launcher Script\n\nUse the provided launcher script that maintains Terminal.app context:\n\n```bash\n./shamon_background.sh\n```\n\n#### Option 3: LaunchAgent (Auto-start at Login)\n\nInstall as a LaunchAgent for persistent operation:\n\n```bash\n# Copy the plist file\ncp com.shamon.music-monitor.plist ~/Library/LaunchAgents/\n\n# Update the paths in the plist file to match your installation directory\nnano ~/Library/LaunchAgents/com.shamon.music-monitor.plist\n\n# Load the service\nlaunchctl load ~/Library/LaunchAgents/com.shamon.music-monitor.plist\n\n# Stop the service\nlaunchctl unload ~/Library/LaunchAgents/com.shamon.music-monitor.plist\n\n# View logs\ntail -f ~/.music_monitor_launchd.log\n```\n\n## Automatic Device Switching\n\nWhen using `--auto-input`, Shamon includes automatic failover between audio devices:\n\n- If the current audio device produces zero audio levels for 3 consecutive checks, it automatically switches to the next available preferred device\n- The preferred devices list is checked in order\n- This ensures continuous monitoring even when devices are disconnected or reconnected\n- The script will cycle through all available preferred devices before giving up\n\nThis feature is especially useful for long-running sessions where USB devices might be temporarily disconnected.\n\n## Web Server\n\nStart the web server to view your music history:\n\n```bash\npython serve.py\n```\n\nThe server runs on port 8080 and provides:\n\n- **http://localhost:8080/** - API information\n- **http://localhost:8080/json** - Song data as JSON (supports `?limit=N` parameter)\n- **http://localhost:8080/table** - Song data as cyberpunk-styled HTML table\n- **http://localhost:8080/stats** - Database statistics\n\n## Database Queries\n\nSongs are stored in `~/.music_monitor.db`. You can query the database directly:\n\n### View Last 10 Songs\n\n```bash\nsqlite3 ~/.music_monitor.db \"SELECT datetime(timestamp, 'localtime'), title, artist FROM songs ORDER BY timestamp DESC LIMIT 10;\"\n```\n\n### View Database Schema\n\n```bash\nsqlite3 ~/.music_monitor.db \".schema\"\n```\n\n### Get Song Count\n\n```bash\nsqlite3 ~/.music_monitor.db \"SELECT COUNT(*) FROM songs;\"\n```\n\n### Find Most Detected Song\n\n```bash\nsqlite3 ~/.music_monitor.db \"SELECT title, artist, COUNT(*) as count FROM songs GROUP BY title, artist ORDER BY count DESC LIMIT 1;\"\n```\n\n## Troubleshooting\n\n### No Audio Devices Found\n\n**Problem:** `Error: No input devices found.`\n\n**Solution:**\n1. Check that your audio device is connected and recognized by macOS:\n   ```bash\n   system_profiler SPAudioDataType\n   ```\n2. Verify SoX can see your devices:\n   ```bash\n   sox -V3 -n -t coreaudio dummy trim 0 1 2\u003e\u00261 | grep \"Found Audio Device\"\n   ```\n3. Try reconnecting your USB audio device\n4. Check System Preferences \u003e Security \u0026 Privacy \u003e Microphone permissions\n\n### Audio Recording Fails\n\n**Problem:** `Audio recording failed. Check device connection.`\n\n**Solution:**\n1. The selected device may be in use by another application\n2. Try closing other audio applications (Zoom, Teams, etc.)\n3. Check microphone permissions in System Preferences\n4. Restart the device or computer\n5. Use a different audio device with `--auto-input`\n\n### Vibra Not Found\n\n**Problem:** `Error: vibra is not installed`\n\n**Solution:**\nInstall Vibra following the instructions at https://github.com/BayernMuller/vibra\n\nFor macOS with Homebrew:\n```bash\nbrew install vibra\n```\n\n### Network Unavailable\n\n**Problem:** `Network unavailable, waiting...`\n\n**Solution:**\n1. Check your internet connection\n2. Verify you can reach external servers:\n   ```bash\n   ping -c 3 8.8.8.8\n   ```\n3. If behind a firewall, ensure outbound connections are allowed\n4. Vibra needs to connect to Shazam's API servers\n\n### Database Locked\n\n**Problem:** SQLite database is locked\n\n**Solution:**\n1. Check if another instance of Shamon is running:\n   ```bash\n   ps aux | grep shamon\n   ```\n2. Kill other instances if found:\n   ```bash\n   pkill -f shamon.sh\n   ```\n3. If problem persists, close any applications accessing the database:\n   ```bash\n   lsof ~/.music_monitor.db\n   ```\n\n### Background Process Stops Working\n\n**Problem:** Headless mode stops detecting music after a while\n\n**Solution:**\n1. Install and use `screen` for better background support:\n   ```bash\n   brew install screen\n   ./shamon.sh --auto-input --headless\n   ```\n2. Check the log file for errors:\n   ```bash\n   tail -f ~/.music_monitor.log\n   ```\n3. Use the LaunchAgent method for persistent operation\n4. Ensure your Mac doesn't sleep (System Preferences \u003e Energy Saver)\n\n### Preferred Device Not Found\n\n**Problem:** `Error: None of the preferred devices found.`\n\n**Solution:**\n1. List available devices without `--auto-input` to see what's available\n2. Update your `~/.shamonrc` with the correct device names:\n   ```bash\n   ./shamon.sh  # Run interactively to see device list\n   ```\n3. Device names must match exactly (case-sensitive)\n\n### No Music Detected\n\n**Problem:** Shamon runs but doesn't detect any music\n\n**Solution:**\n1. Verify audio is being captured:\n   ```bash\n   ./detect_audio_level.sh\n   ```\n2. Check the audio threshold in your config - lower it if needed:\n   ```bash\n   echo \"AUDIO_THRESHOLD=0.005\" \u003e\u003e ~/.shamonrc\n   ```\n3. Increase your system volume\n4. Ensure the correct audio device is selected\n5. Try playing music from a different source\n6. Check debug logs for clues:\n   ```bash\n   ./shamon.sh --debug\n   tail -f ~/.music_monitor.log\n   ```\n\n### Permission Denied on macOS\n\n**Problem:** Terminal doesn't have microphone access\n\n**Solution:**\n1. Go to System Preferences \u003e Security \u0026 Privacy \u003e Privacy \u003e Microphone\n2. Ensure Terminal.app (or iTerm2) has microphone access enabled\n3. You may need to restart Terminal after granting permission\n\n### Web Server Issues\n\n**Problem:** `ModuleNotFoundError: No module named 'fastapi'`\n\n**Solution:**\nInstall Python dependencies:\n```bash\npip install -r requirements.txt\n```\n\n**Problem:** Web server shows \"Database not found\"\n\n**Solution:**\nRun shamon.sh at least once to create the database:\n```bash\n./shamon.sh --auto-input\n# Let it detect at least one song, then Ctrl+C to stop\npython serve.py\n```\n\n## Architecture\n\n### Core Components\n\n1. **Audio Capture** — Uses SoX to record 5-second samples from selected audio device\n2. **Level Detection** — Calculates RMS amplitude to skip silence (threshold: 0.001)\n3. **Normalization** — Boosts audio to -3dB for consistent recognition quality\n4. **Recognition** — Sends normalized audio to Vibra → Shazam API\n5. **Deduplication** — Title-based matching with 60-second time window\n6. **Storage** — SQLite database stores timestamp, title, artist, and audio_level\n7. **Interval Management** — Dynamically adjusts check frequency based on results\n\n### Data Flow\n\n```\nAudio Device → SoX Recording → Level Check → Normalize (-3dB) → Vibra/Shazam → SQLite\n                                    ↓                                              ↓\n                             (Skip if silent)                          Title Matching\n                                                                              ↓\n                                                                 (Skip if duplicate)\n```\n\n## Files\n\n- `shamon.sh` - Main monitoring script\n- `common.sh` - Shared functions library\n- `serve.py` - Web server for viewing data\n- `requirements.txt` - Python dependencies\n- `detect_audio_level.sh` - Audio debugging tool\n- `shamon_daemon.sh` - Daemon mode runner\n- `shamon_background.sh` - macOS background launcher\n- `com.shamon.music-monitor.plist` - LaunchAgent configuration\n- `~/.music_monitor.db` - SQLite database (created on first run)\n- `~/.music_monitor.log` - Debug log file\n- `~/.shamonrc` - User configuration file (optional)\n\n## Version\n\nCurrent version: **1.2.3**\n\n### What's New\n\n**v1.2.3** — Improved song matching and audio detection\n- Audio normalization to -3dB before recognition (detects quieter music)\n- Title-based matching with 60-second time window (handles artist variations)\n- Lower detection threshold (0.001 RMS)\n- Mic-first device fallback priority\n\n**v1.2.2** — Performance and reliability\n- Network check caching (30 seconds)\n- Improved device fallback to any available device\n- XSS fix in web server\n\n**v1.2.1** — Bug fix\n- Fixed parsing of multi-word song titles\n\n**v1.2.0** — Fuzzy matching\n- First-word matching for title and artist\n\n**v1.1.0** — Major refactoring\n- Security fixes (SQL injection prevention)\n- Configuration file support\n- Optimized audio recording\n\n## Contributing\n\nIssues and pull requests are welcome!\n\n## License\n\nCheck the project repository for license information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Froelvangils%2Fshamon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Froelvangils%2Fshamon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Froelvangils%2Fshamon/lists"}