Skip to content

About

Phrase-aware local 4/4 audio loop harvesting, diagnostic metadata, optional transient repair and sampler MIDI helpers

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Beat Chopper

Find the pocket. Cut the loop. Keep the evidence.

Beat Chopper is a local Python command-line toolkit for harvesting phrase-aware 4/4 audio loops from mixes and recordings. The main tool, loop_chopper.py, estimates local tempo, searches for musical boundaries, ranks cuts, and exports WAVs with a JSON audit trail.

Project page · Options · Expansion ideas · GPL-3.0 license

Start with a short slice of audio you own or have permission to use. This is a heuristic loop harvester—not source separation, melodic transcription, a perfect beat detector, or a browser app. Listen before using a cut.

At a glance

Input Process Output
MP3, WAV, AIFF or FLAC; one file or a folder Local tempo → phrase anchors → transient alignment → candidate scoring 44.1 kHz mono, 16-bit PCM WAVs; BPM/key filenames; JSON diagnostics
Exported loops, optionally Rubber Band transient-grid repair Separate warped WAVs and diagnostics
One loop folder, optionally MIDI pad mapping Sample-trigger MIDI or a sample + MIDI bundle for SP-404MKII workflows

Everything runs on your computer; audio is not uploaded. This repository contains code, not a sample library.

Quick start

Use Python 3.9+ (the CLI uses BooleanOptionalAction), with a Python version supported by your installed NumPy/librosa dependencies. macOS has been exercised locally; other operating systems are not certified.

git clone https://github.com/mnicholas7/beat-chopper.git
cd beat-chopper
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python loop_chopper.py --help

On Windows, activate with .venv\Scripts\activate. Rubber Band is optional, not required for chopping. If decoding fails, convert your input to WAV first.

Try a two-minute slice before a full mix:

python loop_chopper.py "audio/my-mix.wav" "output/audition" \
  --offset 120 --duration 120 --bars 4

Then harvest a full file or directory:

python loop_chopper.py "audio/my-mix.wav" "output/loops"
python loop_chopper.py "audio" "output/loops"

Directory scanning is not recursive. Quote paths with spaces. Use fresh output roots for experiments: matching WAVs can be overwritten, old WAVs can remain, and the database describes the current invocation rather than merging all past runs.

How it works

flowchart TD
    source["Audio file or folder"] --> decode["Decode to mono at 44.1 kHz"]
    decode --> tempo["Estimate tempo in local segments"]
    tempo --> features["Spectral evidence: kick, backbeat, crash and harmony"]
    features --> anchors["Find section and phrase anchors"]
    anchors --> candidates["Search nearby sixteenth-note starts"]
    candidates --> score["Rank foundation, edge and grid evidence"]
    score --> choice{"Usable candidate?"}
    choice -->|Yes| export["Export nominal bar-length WAV and metadata"]
    choice -->|No| rescue["Wider salvage search"]
    rescue --> retry{"Recovered?"}
    retry -->|Yes| export
    retry -->|No| skip["Skip unreliable region"]
    export --> advance["Advance scan; retain alternates when enabled"]
    skip --> advance
Loading

Instead of slicing every eight bars from the first beat, it works large to small:

  1. Tempo: default five-minute segments keep long mixes from relying on one global BPM.
  2. Section / phrase: crashes, releases, waveform changes and harmonic evidence help find the musical “one.”
  3. Bar / transient: kick and backbeat evidence rank nearby starts; grid and edge checks help detect pickups and tail leakage.
  4. Audit: metadata explains the cut location, tempo assumptions and alignment warnings.

The default exporter does not time-stretch or post-rotate audio. Repair is a separate, optional step.

Recipes

Fewer overlapping cuts:

python loop_chopper.py INPUT OUTPUT --no-harvest-overlaps --harvest-stride-beats 8

One global tempo analysis:

python loop_chopper.py INPUT OUTPUT --no-dense-harvest --tempo-segment-seconds 0

Both flags matter: dense harvest resets a non-positive segment length to 300 seconds on full-file runs. Turning off dense harvest alone does not reset the other defaults.

Less metadata / no key estimation:

python loop_chopper.py INPUT OUTPUT --no-debug-align --key-mode off

Resume a sorted folder run:

python loop_chopper.py INPUT_DIR OUTPUT --start-at "my-mix.wav"
python loop_chopper.py INPUT_DIR OUTPUT --start-after "my-mix.wav"

Resume flags choose the next source; they do not merge earlier database entries. Back up any database you want to retain.

Handle a detected next-downbeat tail:

python loop_chopper.py INPUT OUTPUT --tail-next-one-mode mute
python loop_chopper.py INPUT OUTPUT --tail-next-one-mode trim

Default off preserves nominal duration. Mute preserves length but silences the detected tail; trim shortens the file. Neither guarantees a fix for internal drift.

Options

Flag Default Purpose
--bars N 8 Target bars per loop; use a positive integer
--limit N 0 Maximum source files; zero means all
--workers N 1 Parallel source processing; increases memory use
--key-mode track / loop / off track Key estimate per source/segment, per loop, or disabled
--offset SECONDS 0 Start later in the source
--duration SECONDS 0 Positive duration analyzes one slice without tempo segmentation
--start-at NAME None Include this filename/stem and later sorted sources
--start-after NAME None Start after it; mutually exclusive with start-at
--debug-align / --no-debug-align On Detailed alignment diagnostics
--flat-output Off Write a single source directly into output root
--dense-harvest / --no-dense-harvest On High-yield profile; restores positive stride/segment defaults
--harvest-overlaps / --no-harvest-overlaps On Keep nearby accepted alternatives
--harvest-max-alternates N 2 Extra cuts per accepted window
--harvest-min-separation-beats N 1.0 Minimum spacing between alternate starts
--harvest-stride-beats N 4.0 Scan advance; non-positive values reset when dense harvest is on
--tempo-segment-seconds N 300 Local tempo segment length; see global-tempo recipe for zero
--tail-next-one-mode off / mute / trim off Leave, silence or remove a detected tail transient

Run each tool's --help for the authoritative CLI. The main chopper has no manual BPM override yet.

Your output

output/loops/
├── my-mix/
│   ├── 000_A_min_122.47BPM_my-mix.wav
│   └── 001_A_min_122.47BPM_my-mix.wav
├── loops_database.json
└── .analysis_cache/

Names contain index, key, decimal BPM and source name. Cuts within each segment are sorted by source time; indexes continue across segments. Different local segments can use different BPM values inside one source folder.

Metadata Explains
start_time / end_time Original source range
bpm / raw_bpm / tempo_normalization Estimated tempo and low-tempo correction
expected_loop_samples / actual_loop_samples / effective_bpm Nominal versus exported duration
phrase_anchor / section_lattice Evidence for the musical starting point
absolute_candidate_score / confident_foundation Candidate selection
tail_next_one_guard Detected next-downbeat intrusion
rhythm_slot_smoke_test Kick/backbeat presence and grid warnings
alignment_debug / phase_debug Detailed diagnostics when debug alignment is enabled

The database is written atomically after completed sources. A rhythm-slot warning is diagnostic, not proof of an unusable loop: sparse arrangements may omit expected hits.

Optional repair and sampler preparation

flowchart LR
    loops["Exported WAV loops"] --> daw["Audition in DAW or sampler"]
    loops --> warp["Optional loop_warper.py + Rubber Band"]
    warp --> repaired["Separate repaired WAVs"]
    loops --> midi["midi_pattern_generator.py"]
    midi --> triggers["MIDI triggers + manifest"]
    loops --> bundle["sp404_pattern_batch.py"]
    bundle --> files["SAMPLES + PATTERNS + manifest"]
Loading

Transient-grid repair

Install the external Rubber Band CLI (for example, brew install rubberband on macOS):

python loop_warper.py "output/loops" "output/warped" --bars 8 --grid beat
python loop_warper.py "output/loops" "output/repair" --bars 8 --repair-profile

Match --bars to your loops: the warper defaults to four bars, the chopper to eight. The warper supports beat/eighth/sixteenth grids, correction thresholds, marker limits and optional exact-length output. It uses Rubber Band's R3 engine without requested pitch shifting. Artifacts remain possible; keep originals and compare by ear.

MIDI / SP-404MKII

python midi_pattern_generator.py "output/loops/my-mix" --output "output/midi"
python sp404_pattern_batch.py "output/loops/my-mix" --output "output/sp404" --max 160

These produce sample-trigger MIDI, not transcription: tempo, 4/4 metadata, one note at beat one, and an end-of-track matching the inferred loop length. Up to 160 samples map to banks A–J, pads 1–16; manifests report channels and notes. Hardware/app import behavior is not certified here; check mappings against your setup.

Known limitation: the shared MIDI filename parser recognizes integer BPM only. Decimal names such as 122.47BPM fall back to 120 BPM in these helpers. Do not trust decimal-tempo bundles until this is fixed, or prepare integer-tempo copies in a separate folder.

Limitations and troubleshooting

  • 4/4 dance assumptions: steady kick/backbeat templates are not a general meter detector.
  • Low-tempo correction: raw estimates below 90 BPM may be multiplied by 1.5 or 2 if that lands in 90–145 BPM. Truly slow music can be mislabelled; inspect raw_bpm.
  • Mono exports: the loader currently downmixes and resamples to 44.1 kHz. Stereo preservation is not implemented.
  • No separation: vocals, melodies and transitions present in the recording remain in each cut.
  • Grid drift: nominal length does not ensure all internal transients are on-grid. Listen before stretching.
  • Key detection is approximate, especially in transitions and dense harmonies.
  • No loops: try a cleaner, steady 4/4 section and inspect the log.
  • Large / slow runs: use a short slice, wider stride, fewer alternates or no-debug-align. Workers multiply memory use.
  • Dependency / decode trouble: try WAV and a fresh virtual environment. Set NUMBA_CACHE_DIR to a writable directory if the automatic macOS-style cache path is unsuitable.
  • Reruns overwrite: use fresh output roots to avoid mixing new and stale cuts.
  • Refresh wrappers are destructive: refresh_mix.sh and refresh_all_mixes.sh delete matching generated output folders first. Inspect --help, pass explicit paths, and never target irreplaceable audio.

Project map

File Role
loop_chopper.py Analysis, selection, WAV export and JSON evidence
loop_warper.py Optional Rubber Band post-pass
sp404_midi_utils.py MIDI writing, pad mapping and duration inference
midi_pattern_generator.py Trigger files for a loop folder
sp404_pattern_batch.py Samples / patterns / manifest bundle
refresh_mix.sh / refresh_all_mixes.sh Destructive rebuild wrappers
requirements.txt NumPy, librosa and soundfile

Expansion ideas

Proposals, not implemented features. Open an issue with a reproducible example using audio you may share.

flowchart TD
    current["Current CLI: WAV loops + JSON evidence"] --> trust["Regression fixtures and confidence reports"]
    current --> control["Manual BPM and configurable meter profiles"]
    current --> browse["Local waveform audition and candidate explorer"]
    current --> fidelity["Stereo-preserving exports"]
    current --> integration["Decimal-tempo MIDI and sampler adapters"]
Loading

Good first projects:

  1. Fix decimal-BPM parsing and add tests.
  2. Add synthetic fixtures for drift, phrase boundaries, silence and half-time errors.
  3. Preserve stereo channels while analyzing a mono reference.
  4. Expose manual BPM and configurable low-tempo normalization.
  5. Build a local waveform explorer with candidate scoring and manual cut adjustment.
  6. Add a durable library index with explicit resume/merge and duplicate detection.

Verification, license and audio rights

Documentation was checked against tracked implementation. Local verification includes CLI help, Python syntax and a synthetic 4/4 WAV smoke run—not a real-mix quality benchmark. This repository currently has no automated test suite.

Code is licensed under GNU GPL v3.0; see LICENSE. This does not grant rights to source recordings or compositions. Only chop audio you own or are permitted to use; do not upload copyrighted recordings or private databases in issues.

About

Phrase-aware local 4/4 audio loop harvesting, diagnostic metadata, optional transient repair and sampler MIDI helpers

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages