File size: 2,329 Bytes
487c77e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from utils.audio_utils import detect_beats_and_tempo
from utils.video_utils import cut_and_sync_videos, apply_video_effects
import os
import moviepy.editor as mp
import gradio as gr

def process_music_video(music_path, file_paths, num_files, image_duration_beats, selected_effect, progress=gr.Progress()):
    """

    Processes the music and video/image files with a user-selected beat-synchronized effect.

    """
    beat_times, tempo = detect_beats_and_tempo(music_path,image_duration_beats)
    audio_clip = None  # Initialize audio_clip outside the try block

    # Calculate the desired audio duration
    if len(beat_times) > num_files:
        audio_end_time = beat_times[num_files]
    else:
        audio_end_time = beat_times[-1] if beat_times else 5.0

    progress(0.1, desc="Analyzing audio and determining trim length...")

    try:
        audio_clip = mp.AudioFileClip(music_path).subclip(0, audio_end_time)

        # Calculate image duration in seconds
        if beat_times is not None and len(beat_times) > 0:
            if image_duration_beats <= len(beat_times) - 1:
                image_duration_seconds = beat_times[image_duration_beats] - beat_times[0] if image_duration_beats > 0 else beat_times[0]
            else:
                image_duration_seconds = 2.0
        else:
            image_duration_seconds = 2.0

        progress(0.3, desc="Syncing video/image clips...")
        result = cut_and_sync_videos(file_paths, beat_times[:num_files], image_duration_seconds=image_duration_seconds)

        if result:
            final_video, base_clips = result

            progress(0.6, desc="Applying video effects...")
            final_video = apply_video_effects(final_video, beat_times[:num_files], selected_effect=selected_effect)

            progress(0.8, desc="Merging audio and rendering final video...")
            final_video = final_video.set_audio(audio_clip)

            output_video_path = "output.mp4"
            final_video.write_videofile(output_video_path, fps=24, codec="libx264")
            final_video.close()
            for clip in base_clips:
                clip.close()
            return output_video_path
        else:
            return None
    finally:
        if audio_clip:
            audio_clip.close()