Creating a script to automatically generate videos similar to the TikTok marble run trend from a MIDI file involves several steps:
- Parse the MIDI File: Extract musical notes and timing information.
- Map MIDI Notes to Visual Events: Associate each MIDI note with a marble movement or event in the marble run.
- Simulate the Marble Run: Create visual representations of the marble run synchronized with the music.
- Generate Video Frames: Render each frame of the animation based on the simulation.
- Combine Frames and Audio into a Video: Compile the frames into an MP4 video and synchronize it with the MIDI audio.
Below is a comprehensive guide using Python, leveraging libraries such as mido for MIDI parsing, pygame for simulation and rendering, and moviepy for final video creation.
Prerequisites
-
Install Required Libraries
pip install mido pygame moviepy
-
Convert MIDI to Audio
Since moviepy works better with standard audio formats like MP3 or WAV, you might need to convert MIDI to WAV. Tools like Timidity can help:
sudo apt-get install timidity
timidity input.mid -Ow -o output.wav
Step-by-Step Implementation
1. Parse the MIDI File
Use the mido library to extract note events and their timing.
import mido
def parse_midi(midi_file):
mid = mido.MidiFile(midi_file)
notes = []
current_time = 0
for msg in mid:
current_time += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
notes.append({'time': current_time, 'note': msg.note})
return notes, mid.length
2. Map MIDI Notes to Marble Events
Define how each MIDI note corresponds to a specific marble movement or event. For simplicity, let's map different notes to different marble colors or paths.
def map_notes_to_events(notes):
events = []
for note in notes:
# Example mapping: Different pitch ranges map to different marble colors
if 60 <= note['note'] < 72:
color = (255, 0, 0) # Red
elif 72 <= note['note'] < 84:
color = (0, 255, 0) # Green
else:
color = (0, 0, 255) # Blue
events.append({'time': note['time'], 'color': color})
return events
3. Simulate the Marble Run Using Pygame
Create a simple simulation where marbles appear based on MIDI events.
import pygame
import sys
def simulate_marble_run(events, duration, output_folder='frames', fps=30):
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Marble Run Simulation')
clock = pygame.time.Clock()
marbles = []
current_event = 0
total_frames = int(duration * fps)
import os
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for frame in range(total_frames):
current_time = frame / fps
# Handle events
while current_event < len(events) and events[current_event]['time'] <= current_time:
marble = {
'color': events[current_event]['color'],
'position': [width // 2, height],
'velocity': [0, -5] # Simple upward movement
}
marbles.append(marble)
current_event += 1
# Update marble positions
for marble in marbles:
marble['position'][0] += marble['velocity'][0]
marble['position'][1] += marble['velocity'][1]
# Simple gravity simulation
marble['velocity'][1] += 0.1
# Remove marbles that are out of screen
marbles = [m for m in marbles if m['position'][1] < height]
# Draw
screen.fill((0, 0, 0)) # Black background
for marble in marbles:
pygame.draw.circle(screen, marble['color'], (int(marble['position'][0]), int(marble['position'][1])), 10)
# Save frame
pygame.display.flip()
pygame.image.save(screen, f"{output_folder}/frame_{frame:05d}.png")
clock.tick(fps)
pygame.quit()
Note: This is a very basic simulation. For a more intricate marble run, you'd need to implement physics, tracks, collisions, etc., possibly leveraging more advanced libraries or game engines like Pygame, Panda3D, or Godot with Python scripting.
4. Combine Frames and Audio into a Video
Use moviepy to compile the frames into a video and add the audio track.
from moviepy.editor import ImageSequenceClip, AudioFileClip
def create_video(frame_folder, audio_file, output_file='output.mp4', fps=30):
# Gather frame file paths
import glob
frame_files = sorted(glob.glob(f"{frame_folder}/frame_*.png"))
# Create video clip from images
clip = ImageSequenceClip(frame_files, fps=fps)
# Add audio
audio = AudioFileClip(audio_file)
clip = clip.set_audio(audio)
# Write the video file
clip.write_videofile(output_file, codec='libx264', audio_codec='aac')
5. Putting It All Together
Here's how you can integrate all the steps into a single script.
import os
def generate_marble_run_video(midi_input, output_video='output.mp4'):
# Step 1: Parse MIDI
notes, duration = parse_midi(midi_input)
# Step 2: Map notes to events
events = map_notes_to_events(notes)
# Step 3: Simulate and generate frames
simulate_marble_run(events, duration, output_folder='frames', fps=30)
# Step 4: Convert MIDI to WAV (requires external tool, ensure 'timidity' is installed)
audio_output = 'output.wav'
os.system(f"timidity {midi_input} -Ow -o {audio_output}")
# Step 5: Create video
create_video('frames', audio_output, output_video=output_video, fps=30)
print(f"Video generated: {output_video}")
if __name__ == "__main__":
midi_file = 'input.mid' # Replace with your MIDI file path
generate_marble_run_video(midi_file, 'marble_run.mp4')
6. Usage Instructions
-
Prepare Your MIDI File: Ensure you have a MIDI file (input.mid) in your working directory.
-
Run the Script: Save the above script to a Python file, e.g., marble_run_generator.py, and execute it:
python marble_run_generator.py
-
Wait for Processing: The script will parse the MIDI, simulate the marble run by generating frames, convert the MIDI to WAV, and compile everything into marble_run.mp4.
-
View Your Video: Once completed, you'll have an MP4 video visualizing the marble run synchronized with your MIDI music.
Enhancements and Considerations
-
Advanced Visuals: The provided simulation is rudimentary. To create more sophisticated marble runs, consider using advanced graphics libraries or game engines that support physics simulations.
-
Real Marble Run Integration: If you wish to use an actual marble run mechanism, automation would require hardware integration (e.g., with Arduino or Raspberry Pi) to control the marbles, which is significantly more complex.
-
Performance Optimization: Generating a large number of high-resolution frames can be resource-intensive. Optimize the simulation and rendering process as needed.
-
Error Handling: Incorporate error checks, especially for external tool dependencies like timidity.
-
Customization: Allow users to customize color mappings, marble behaviors, and track designs to create unique videos.
Conclusion
While the above script provides a foundational approach to generating a marble run video from a MIDI file, creating high-quality and intricate animations can become complex. Depending on your requirements, you might explore more powerful tools or frameworks tailored for animation and video generation. Nonetheless, this guide offers a starting point to automate the creation of synchronized music and marble run visualizations.