Syncs a Blender animation to music - finds the beats in the user's audio file inside Blender (no extra packages), keys hits on every beat (scale, emission, any property), cuts cameras on the bars, and renders a video with the song mixed in, vertical for Reels, Shorts and TikTok or any size. Use when a user wants a music video, a beat-synced loop, a lyric or logo animation that hits on the beat, or a 3D clip for a track.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Blender Beat Sync?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jasmylab-janction-blender-beat-sync)
---
name: blender-beat-sync
description: Syncs a Blender animation to music - finds the beats in the user's audio file inside Blender (no extra packages), keys hits on every beat (scale, emission, any property), cuts cameras on the bars, and renders a video with the song mixed in, vertical for Reels, Shorts and TikTok or any size. Use when a user wants a music video, a beat-synced loop, a lyric or logo animation that hits on the beat, or a 3D clip for a track.
license: MIT
metadata:
author: JasmyLab Inc. (https://render.janction.jp)
version: "0.1.0"
related-skills: blender-animation-delivery, blender-render-settings, blender-turntable
---
# Blender Beat Sync
A beat-synced clip fails in three ways: the beats are found in the wrong place (on the hi-hats, half a beat off), the
grid drifts so the end of the song is late, or the video plays at a different FPS from the one the keys were placed at.
Find the beats once, convert them to frames with the FPS the video will play at, and check the finished file.
Use only audio the user may use: their own track, a licensed one, or a royalty-free one. Do not pull songs from the
web.
## Finding the beats inside Blender
Blender reads WAV, MP3, OGG and FLAC through its `aud` module and ships numpy, so this runs in any Blender 5.x with no
installs, locally or on a render service. Tested on Blender 5.0 and 5.2.
```python
import bpy, math, os
import numpy as np
from mathutils import Vector
def read_audio(path):
import aud
snd = aud.Sound(path)
return snd.data().mean(axis=1).astype(np.float32), int(snd.specs[0])
def find_beats(path, bpm=None, min_bpm=70, max_bpm=180, hop=256, win=1024):
"""Beat times in seconds and the tempo. Pass bpm when the user knows it; the phase still comes from the audio."""
x, sr = read_audio(path)
n = 1 + max(0, (len(x) - win) // hop)
idx = np.arange(win)[None, :] + hop * np.arange(n)[:, None]
mag = np.abs(np.fft.rfft(x[idx] * np.hanning(win), axis=1))
rate = sr / hop
k = max(1, int(0.4 * rate))
smooth = np.hanning(5) / np.hanning(5).sum()
def onsets(band):
flux = np.maximum(0.0, np.diff(np.log1p(100 * band), axis=0)).sum(axis=1)
e = np.concatenate([[0.0], flux])
e = np.maximum(0.0, e - np.convolve(e, np.ones(k) / k, mode="same")) # remove the slow trend
e = np.convolve(e, smooth, mode="same")
return e / (e.std() + 1e-9)
# the beat sits on the kick and the bass (below about 200 Hz), not on the hi-hats
low, full = onsets(mag[:, :max(2, int(200 * win / sr))]), onsets(mag)
env = low + 0.25 * full if np.percentile(low, 99) > 3 * np.percentile(low, 50) + 1 else full
if bpm:
period = 60.0 * rate / bpm
else:
ac = np.correlate(env, env, mode="full")[len(env) - 1:]
lags = np.arange(int(rate * 60 / max_bpm), int(rate * 60 / min_bpm) + 1)
weight = np.exp(-0.5 * (np.log2((60.0 * rate / lags) / 120.0) / 0.9) ** 2)
period = float(lags[np.argmax(ac[lags] * weight)])
best = (-1.0, period, 0.0) # refine period and phase together: whole frames drift
for per in period * (1 + np.linspace(-0.015, 0.015, 61)):
for ph in np.arange(0.0, per, 0.5):
sc = env[np.round(np.arange(ph, len(env) - 1, per)).astype(int)].sum()
if sc > best[0]:
best = (sc, per, ph)
_, period, phase = best
grid = np.arange(phase, len(env) - 1, period)
r = max(1, int(0.04 * rate)) # snap each beat to the onset within 40 ms
pos, strength = [], []
for g in grid:
lo, hi = max(0, int(round(g)) - r), min(len(env), int(round(g)) + r + 1)
j = lo + int(np.argmax(env[lo:hi]))
pos.append(j)
strength.append(env[j])
pos, strength = np.array(pos, float), np.array(strength)
keep = strength > 0.35 * np.percentile(strength, 75)
i = np.arange(len(grid))
if keep.sum() >= 4: # one straight line through the real onsets: no drift
slope, icpt = np.polyfit(i[keep], pos[keep], 1, w=strength[keep])
period = slope
grid = (icpt + slope * i)[(i >= i[keep][0]) & (i <= i[keep][-1])]
beats = (grid * hop + win / 2) / sr - 0.5 * hop / sr
return [float(t) for t in beats if t >= 0], float(60.0 * rate / period)
```
Measured on synthetic tracks with known beats (84, 97, 100, 120, 128 and 140 BPM, with noise and offbeat hi-hats):
every beat within 9 ms, a quarter of a frame at 30 FPS. A 174 BPM track came back as 87: the tempo is right, the
count is half. When the found BPM is half or double what the user hears, pass `bpm=` with the right number.
## Sound, frames and hits
```python
def add_music(path, fps, frame_start=1):
"""The song as a sound strip (it plays in the rendered video) and the frame range set to its length."""
import aud
s = bpy.context.scene
s.render.fps, s.render.fps_base = fps, 1.0
s.sequence_editor_create()
s.sequence_editor.strips.new_sound("music", path, channel=1, frame_start=frame_start)
snd = aud.Sound(path)
s.frame_start = frame_start
s.frame_end = frame_start + math.ceil(snd.length / snd.specs[0] * fps) - 1
def beat_frames(beats, fps, frame_start=1):
return [frame_start + round(t * fps) for t in beats]
def pulse(owner, path, frames, peak, rest, decay=6):
"""Rest one frame before the beat, peak on it, back to rest after `decay` frames.
(obj, "scale"), (obj, "location"), (socket, "default_value") ... anything keyframe_insert takes."""
gap = min(b - a for a, b in zip(frames, frames[1:])) if len(frames) > 1 else decay + 2
decay = max(1, min(decay, gap - 2))
for f in frames:
for frame, value in ((f - 1, rest), (f, peak), (f + decay, rest)):
setattr(owner, path, value)
owner.keyframe_insert(path, frame=frame)
def cut_on_bars(cameras, frames, beats_per_bar=4, bar_offset=0):
"""Switch the active camera on every bar with timeline markers bound to cameras (renders honour them)."""
s = bpy.context.scene
for n, f in enumerate(frames[bar_offset::beats_per_bar]):
m = s.timeline_markers.new(f"bar{n + 1}", frame=f if n else s.frame_start)
m.camera = cameras[n % len(cameras)]
s.camera = cameras[0]
```
`sequence_editor.strips` is the Blender 5 name (4.x called it `sequences`). The first found beat is treated as the
downbeat; if the cuts land on beat 2, pass `bar_offset=1` (or 2, 3).
## The tested example
Twelve balls in four rows: every ball bounces on every beat and the light runs one row per beat, three cameras cut on
the bars, 1080x1920 at 30 FPS for a vertical post.
```python
music = os.path.join(os.environ.get("JR_ASSETS_DIR", "."), "track.wav")
FPS = 30
add_music(music, FPS)
beats, bpm = find_beats(music)
frames = beat_frames(beats, FPS)
print(f"JR_BEATS bpm={bpm:.2f} first={beats[0]:.3f}s count={len(beats)}")
for o in list(bpy.data.objects):
bpy.data.objects.remove(o, do_unlink=True)
s = bpy.context.scene
bpy.ops.mesh.primitive_plane_add(size=40)
floor = bpy.data.materials.new("Floor")
fb = floor.node_tree.nodes["Principled BSDF"]
fb.inputs["Base Color"].default_value, fb.inputs["Roughness"].default_value = (0.02, 0.02, 0.025, 1), 0.25
bpy.context.object.data.materials.append(floor)
palette = [(1.0, 0.25, 0.1), (0.1, 0.55, 1.0), (1.0, 0.85, 0.2), (0.7, 0.2, 1.0)]
balls = []
for row in range(4):
for col in range(3):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.34, location=((col - 1) * 0.95, (row - 1.5) * 0.95, 0.34),
segments=48, ring_count=24)
ball = bpy.context.object
bpy.ops.object.shade_smooth()
m = bpy.data.materials.new(f"Ball{row}{col}")
bsdf = m.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = bsdf.inputs["Emission Color"].default_value = (*palette[row], 1)
bsdf.inputs["Roughness"].default_value = 0.3
ball.data.materials.append(m)
balls.append((ball, bsdf, row))
bpy.context.preferences.edit.keyframe_new_interpolation_type = "BEZIER"
for ball, bsdf, row in balls:
pulse(ball, "scale", frames, Vector((1.12, 1.12, 1.12)), Vector((1.0, 1.0, 1.0)), decay=7) # every beat
mine = [f for n, f in enumerate(frames) if n % 4 == row] # beat n lights row n % 4
pulse(bsdf.inputs["Emission Strength"], "default_value", mine, 2.5, 0.05, decay=10)
s.world = bpy.data.worlds.new("Dark")
bg = s.world.node_tree.nodes.get("Background") if s.world.node_tree else None
if bg is not None:
bg.inputs["Color"].default_value = (0.002, 0.002, 0.003, 1)
bpy.ops.object.light_add(type="AREA", location=(0, -3, 5), rotation=(math.radians(35), 0, 0))
bpy.context.object.data.energy, bpy.context.object.data.size = 250, 3
aim = bpy.data.objects.new("Aim", None)
s.collection.objects.link(aim)
cameras = []
for name, loc in (("CAM_Wide", (0, -4.9, 3.1)), ("CAM_Low", (3.0, -3.7, 1.5)), ("CAM_Top", (0.01, -0.6, 7.2))):
cam = bpy.data.objects.new(name, bpy.data.cameras.new(name))
cam.data.lens, cam.location = 30, loc
s.collection.objects.link(cam)
t = cam.constraints.new("TRACK_TO")
t.target, t.track_axis, t.up_axis = aim, "TRACK_NEGATIVE_Z", "UP_Y"
cameras.append(cam)
cut_on_bars(cameras, frames)
s.render.use_motion_blur = False
```
Keep emission peaks modest (2-3 with AgX): stronger flashes wash every colour to white. Leave motion blur off so the
hit frame stays sharp.
## Rendering on JANCTION Render (no local GPU)
1. `render_preview(scene_script=..., assets=['<path to the audio file>'], frames='<a beat frame>,<the next beat>,...')`
shows the hits and the cuts; the script prints the BPM and the first beat (`script_output`).
2. `render_final(..., width=1080, height=1920, fps=30, samples=32, test='contiguous')`: 10 frames on the final path,
the measured time and the price of the whole song. The reply's warnings say the strip was mixed into the video.
3. The full range after the user agrees. Over 240 frames it runs in parts and comes back as one MP4 with the sound.
Pass the same `fps` to `render_final` as the script used: for a script scene the service does not read the scene's
FPS (its default is 24), and the keys sit on 30 FPS frames. The audio file travels in `assets` and arrives under
`JR_ASSETS_DIR` with its own name.
Measured on the example (8.6 s, 258 frames, 1080x1920, 32 samples): 2.2 GPU seconds per frame, 724 GPU seconds
in two parts, about 3 minutes, 46 JPY plus 2 JPY for the test. In the delivered MP4 all 17 beats landed on the
frame where the light jumps (0 frames off), with AAC 48 kHz stereo for the full 8.6 s.
Locally, render straight to a video with the sound (`blender -b -P scene.py -a`):
```python
r = bpy.context.scene.render
if hasattr(r.image_settings, "media_type"):
r.image_settings.media_type = "VIDEO" # Blender 5: choose video before FFMPEG
r.image_settings.file_format = "FFMPEG"
r.ffmpeg.format, r.ffmpeg.codec, r.ffmpeg.audio_codec = "MPEG4", "H264", "AAC"
r.filepath = "/absolute/path/clip.mp4" # '//' has no folder when the .blend is not saved
```
## Check the finished video
The beat must land on the hit in the file people will watch, not only in Blender.
```python
import subprocess, numpy as np, wave
subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", "output.mp4", "-ac", "1", "-ar", "44100", "a.wav"], check=True)
with wave.open("a.wav") as w:
sr, y = w.getframerate(), np.frombuffer(w.readframes(w.getnframes()), "<i2").astype(np.float32) / 32768
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", "output.mp4", "-vf", "scale=54:96,format=gray", "-f", "rawvideo", "-"],
capture_output=True, check=True).stdout
fps = 30
light = np.frombuffer(raw, np.uint8).reshape(-1, 96 * 54).mean(axis=1)
hits = [f for f in range(1, len(light)) if light[f] - light[f - 1] > 4] # frames where the light jumps up
# beats of the audio in the file: find_beats with this reader instead of aud
```
Run `find_beats` on `a.wav` (outside Blender, replace `read_audio` with the `wave` reader above) and compare each beat
`round(t * fps)` with the nearest entry in `hits`: every beat should match a hit within one frame. Also check
`ffprobe` for one audio and one video stream and the expected duration.
## When it goes wrong
| Symptom | Cause | Fix |
|---|---|---|
| Hits land between the beats | Locked on the hi-hats | The low-band envelope above; or pass `bpm=` |
| Hits drift late by the end | Tempo rounded to whole frames | The joint period-phase search and the line fit above |
| Everything is late or early by the same amount | Video FPS differs from the FPS the keys used | Same `fps` in the script and the render |
| Half as many hits as beats | Tempo found at half | `bpm=` with the tempo the user hears |
| Silent video | No sound strip, or a local render without an audio codec | `add_music`; locally set FFmpeg audio to AAC |
| `AttributeError: sequences` | Blender 5 renamed it | `sequence_editor.strips` |