agentsclimarketplace

Audio sync

Skill ahmedhassan456/manim-skills/skills/audio-sync

Time Manim animations to music and sound — Scene.add_sound for one-off effects, extracting beat and onset times from an audio file, driving animation timing from a BPM grid, building audio-reactive visuals from amplitude or spectrum envelopes, and mixing music under narration. Use whenever animation must land on a beat, react to sound, or carry a soundtrack.From its SKILL.md

Install
npx -y skills add ahmedhassan456/manim-skills --skill audio-sync

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
  • 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

8.2 KB, as published. Nobody here has run it

Syncing animation to audio

There are two distinct problems here, and they need different tools:

ProblemApproach
A sound should play at a moment in the animationself.add_sound(...) inside the scene
The animation should be timed to the audioanalyse the audio first, then build the scene from the timings

The second is the interesting one, and the trap is trying to do it by ear. Guessing run_time values until things look aligned does not converge. Extract the real beat times, then make every run_time a computed interval between them.

For spoken narration rather than music, use the manim-voiceover plugin instead — it times animations to speech and is covered in the manim skill's references/voiceovers.md.

One-off sounds

add_sound(sound_file, time_offset=0, gain=None, **kwargs)
class Ping(Scene):
    def construct(self):
        dot = Dot()
        self.add_sound("assets/click.wav")           # plays at the current scene time
        self.play(FadeIn(dot))

        self.add_sound("assets/whoosh.wav", gain=-6) # 6 dB quieter
        self.play(dot.animate.shift(RIGHT * 3))
  • The sound is placed at the scene's current time, so where the call sits between play calls is what determines timing.
  • time_offset skips into the file; it does not delay playback.
  • gain is in decibels; negative is quieter.
  • Manim mixes these into the final video's audio track. They do not appear when rendering with -s (single frame) or --format=gif.
  • Paths resolve relative to the current working directory, not the scene file. Use absolute paths or run manim from the project root.

Getting real timings out of an audio file

Install librosa (analysis) alongside soundfile:

pip install librosa soundfile

Beat grid

import librosa

y, sr = librosa.load("music.wav", sr=None, mono=True)
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr, units="frames")
beat_times = librosa.frames_to_time(beat_frames, sr=sr)   # seconds, ndarray

print(float(tempo), beat_times[:8])

Cache this. Analysis takes seconds and the answer never changes for a given file — write it to JSON and have the scene read that, so re-rendering does not re-analyse:

import json, pathlib

CACHE = pathlib.Path("beats.json")
if CACHE.exists():
    beat_times = json.loads(CACHE.read_text())
else:
    y, sr = librosa.load("music.wav", sr=None, mono=True)
    _, frames = librosa.beat.beat_track(y=y, sr=sr, units="frames")
    beat_times = librosa.frames_to_time(frames, sr=sr).tolist()
    CACHE.write_text(json.dumps(beat_times))

Onsets (every transient, not just the pulse)

onset_times = librosa.onset.onset_detect(y=y, sr=sr, units="time", backtrack=True)

Use onsets for percussive hits and note starts; use beats for the underlying grid. backtrack=True moves each onset back to the nearest preceding energy minimum, which lands closer to where the sound actually starts.

Amplitude envelope, sampled per video frame

import numpy as np

FPS = 60
hop = sr // FPS                                  # one analysis frame per video frame
rms = librosa.feature.rms(y=y, frame_length=2048, hop_length=hop)[0]
env = rms / rms.max()                            # normalise to 0..1

env[i] is now the loudness at video frame i — exactly what an updater needs.

Building the scene from the timings

The key move: derive every run_time from the gaps between events, never from a literal.

from manim import *
import json

beat_times = json.loads(open("beats.json").read())

class OnBeat(Scene):
    def construct(self):
        self.add_sound("music.wav")

        dot = Dot(color=YELLOW).scale(2)
        self.add(dot)

        # Wait until the first beat
        if beat_times[0] > 0:
            self.wait(beat_times[0])

        # One pulse per beat, each lasting exactly until the next
        for t0, t1 in zip(beat_times, beat_times[1:]):
            self.play(
                Flash(dot, color=YELLOW, line_length=0.4),
                dot.animate.scale(1.3),
                run_time=(t1 - t0) * 0.4,
            )
            self.play(dot.animate.scale(1 / 1.3), run_time=(t1 - t0) * 0.6)

Because the two run_times sum to exactly t1 - t0, error cannot accumulate. Compare with using run_time=0.5 per beat, which drifts out of sync within twenty seconds on any real track.

A fixed BPM grid, when you know the tempo

BPM = 128
BEAT = 60 / BPM              # 0.46875 s

self.play(Create(square), run_time=BEAT * 2)     # two beats
self.play(Rotate(square, PI), run_time=BEAT * 4) # one bar in 4/4

Set config.frame_rate so that a beat is a whole number of frames if you can — at 60 fps and 128 BPM a beat is 28.125 frames, and the quarter-frame residue is visible as jitter on fast cuts. Either pick a frame rate that divides evenly, or accept it and avoid sub-beat cuts.

Audio-reactive visuals

Drive a ValueTracker from the envelope with a dt-based updater:

class Reactive(Scene):
    def construct(self):
        self.add_sound("music.wav")

        level = ValueTracker(0)
        bar = Rectangle(width=1, height=0.1, fill_opacity=1, color=BLUE)
        bar.to_edge(DOWN, buff=1)
        self.add(bar)

        bar.add_updater(
            lambda m: m.stretch_to_fit_height(0.1 + 5 * level.get_value())
                       .to_edge(DOWN, buff=1)
        )

        elapsed = ValueTracker(0)

        def follow_audio(m, dt):
            elapsed.increment_value(dt)
            i = min(int(elapsed.get_value() * FPS), len(env) - 1)
            level.set_value(float(env[i]))

        bar.add_updater(follow_audio)
        self.wait(len(env) / FPS)

Two things to watch:

  • Anchor after stretching. stretch_to_fit_height grows about the centre, so without the to_edge the bar creeps upward. This is the most common bug in reactive visuals.
  • Use the scene clock, not real time. Accumulating dt (as above) stays correct at any render speed. Reading time.time() works in preview and desyncs completely in a -qh render, which runs far slower than real time.

A spectrum instead of a single level:

S = np.abs(librosa.stft(y, n_fft=2048, hop_length=hop))
mel = librosa.feature.melspectrogram(S=S**2, sr=sr, n_mels=32)
mel_db = librosa.power_to_db(mel, ref=np.max)
bands = (mel_db - mel_db.min()) / (mel_db.max() - mel_db.min())   # (32, n_frames), 0..1

bands[:, i] is a 32-band spectrum for video frame i — one bar per row.

Mixing the final soundtrack

add_sound is fine for effects, but for a real music bed under narration, mux with ffmpeg after rendering — you get level control and can iterate without re-rendering the animation:

# Music at 25% under narration, normalised for YouTube
ffmpeg -i render.mp4 -i narration.wav -i music.mp3 \
  -filter_complex "[2:a]volume=0.25[m];[1:a][m]amix=inputs=2:duration=first[a]" \
  -map 0:v -map "[a]" -c:v copy -c:a aac -b:a 192k -af loudnorm=I=-14:TP=-1.5 final.mp4

See the video-post skill for ducking, loudness normalisation and export presets.

Gotchas

SymptomCause
Audio missing from the outputRendered with -s, or to --format=gif; neither carries an audio track
Sync drifts over the videoLiteral run_time values instead of intervals computed from event times
Sound plays at the wrong momentadd_sound fires at the scene time where the call sits — move the call, not the offset
Reactive visual freezesThe updater reads past the end of the envelope array — clamp the index
Reactive visual drifts off-positionA stretch/scale updater without a re-anchor (to_edge, move_to)
Works in preview, desyncs at -qhThe updater uses wall-clock time instead of accumulated dt
librosa import is very slowExpected on first import; another reason to cache the analysis to JSON

Keep looking

Skills are one crate of 607,533. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.