Moviepy Python – добавление счетчика чисел к видео для каждого повторения мантры 108 разPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Moviepy Python – добавление счетчика чисел к видео для каждого повторения мантры 108 раз

Сообщение Anonymous »

Я пытаюсь создать видео, используя Moviepy версии 2 и Python. скрипт принимает изображение, воспроизводит звук и создает видео. В основном это повторение мантры 108 раз. В приведенном ниже сценарии я могу создать видео для статического изображения, но не могу наложить счетчик чисел. Я хочу отображать номера для каждого пения до 108. Как добиться, не могу получить, пожалуйста, помогите. Я использую приведенный ниже сценарий
from moviepy import AudioFileClip, ImageClip, CompositeAudioClip, TextClip, CompositeVideoClip, DataVideoClip
from moviepy import vfx, afx
from pedalboard.io import AudioFile
from pedalboard import Pedalboard, NoiseGate, Compressor, LowShelfFilter, Gain
import noisereduce as nr
from pydub import AudioSegment
import os
#import multiprocessing

def process_audio(input_audio_path, output_audio_path):
"""
Processes the input audio by scaling it 108 times, reducing noise, and applying effects.
"""
print("Processing audio...")

# Step 1: Load and scale the audio file by repeating it 108 times
audio = AudioSegment.from_file(input_audio_path)
scaled_audio = audio * 108 # Repeat the audio 108 times
temp_scaled_audio_path = "scaled_audio_temp.mp3"
scaled_audio.export(temp_scaled_audio_path, format="mp3") # Save temporarily

# Step 2: Set up parameters for noise reduction and effects processing
sr = 44100

# Load the scaled audio for noise reduction and effects
with AudioFile(temp_scaled_audio_path).resampled_to(sr) as f:
audio_data = f.read(f.frames)

# Step 3: Reduce noise
reduced_noise = nr.reduce_noise(y=audio_data, sr=sr, stationary=True, prop_decrease=0.75)

# Step 4: Set up the pedalboard effects
board = Pedalboard([
NoiseGate(threshold_db=-25, ratio=1.5, release_ms=200),
Compressor(threshold_db=-12, ratio=3.0),
LowShelfFilter(cutoff_frequency_hz=400, gain_db=6, q=1),
Gain(gain_db=6)
])

# Step 5: Apply effects to the reduced noise audio
effected = board(reduced_noise, sr)

# Step 6: Save the enhanced audio to a new file
with AudioFile(output_audio_path, 'w', sr, effected.shape[0]) as f:
f.write(effected)

# Clean up temporary file
os.remove(temp_scaled_audio_path)
print(f"Enhanced audio file saved as {output_audio_path}")

def create_text_clip(i, duration, font, font_size, text_color):
print(f"{i}")
text_clip = TextClip(text=f"{i}.", font=font, font_size=font_size, color=text_color)
text_clip = text_clip.with_position(("right", "bottom")).with_duration(duration)

return text_clip

def create_video_with_audio(image_path, chant_audio_path, bgm_audio_path, output_path, resolution=(1920, 1080), fps=30):
"""
Creates a video from a static image, main chant audio, and background music.
"""
print("Creating video...")

# Step 1: Load the main chant audio
chant_audio = AudioFileClip(chant_audio_path)

chant_audio =chant_audio.with_effects([afx.MultiplyVolume(2.2)])

# Step 2: Load the background music audio
bgm_audio = AudioFileClip(bgm_audio_path)

bgm_audio =bgm_audio.with_effects([afx.MultiplyVolume(0.2)])

# Step 3: Create an image clip from the static image
image_clip = ImageClip(image_path)

# Resize the image clip to the desired resolution
image_clip = image_clip.with_effects([vfx.Resize(resolution)])

# Step 4: Set the duration of the image clip to match the duration of the chant audio
image_clip = image_clip.with_duration(chant_audio.duration)

# Step 5: Combine both audio tracks
final_audio = CompositeAudioClip([chant_audio.with_volume_scaled(2), bgm_audio.with_volume_scaled(0.3)]) # Adjust volumes as needed
#final_audio = CompositeAudioClip([chant_audio, bgm_audio]) # Adjust volumes as needed

# Step 6: Set the combined audio to the image clip
video_clip = image_clip.with_audio(final_audio)

# Step 7: Create text clips for numbering
font = "C:\\Windows\\Fonts\\arialbd.ttf" # Change font if desired
font_size = 48 # Adjust font size as needed
text_color = "white" # Change text color if desired

# Loop through each repetition (assuming 108 repetitions)
# Create a pool of processes for parallel text clip creation and composition
#with multiprocessing.Pool() as pool:
#print("i am inside")
#text_clips = pool.starmap(create_text_clip, [(i, chant_audio.duration, font, font_size, text_color) for i in range(1, 109)])
text_clips = []
for i in range(1, 109):
text_clip = create_text_clip(i, chant_audio.duration, font, font_size, text_color)
text_clips.append(text_clip)
print(text_clips)

#video_clip1 = text_clips.write_videofile("result1.mp4", fps=fps)

# Combine the video clip with the text clip for this repetition
print("video clip")
video_clip = CompositeVideoClip([video_clip] +text_clips)

# Step 7: Write the resulting video file
video_clip.write_videofile(output_path, fps=fps, bitrate="5000k")
print(f"Video file saved as {output_path}")

if __name__ == "__main__":
# Hardcoded paths
image_path = "C:\\Users\\GuruprasadChandrashe\\Videos\\Youtube_Proj\\workingFolder\\image.png" # Path to the static image
input_audio_path = "C:\\Users\\GuruprasadChandrashe\\Videos\\Youtube_Proj\\workingFolder\\chant_audio.mp3" # Path to the chant audio
input_bgm_audio_path = "C:\\Users\\GuruprasadChandrashe\\Videos\\Youtube_Proj\\workingFolder\\tanpura_C.mp3" # Path to the background music
processed_audio_path = "C:\\Users\\GuruprasadChandrashe\\Videos\\Youtube_Proj\\workingFolder\\processed_chant_audio.mp3" # Processed chant audio output
output_video_path = "C:\\Users\\GuruprasadChandrashe\\Videos\\Youtube_Proj\\workingFolder\\final_video.mp4" # Output video file

# Step 1: Process the input chant audio
#process_audio(input_audio_path, processed_audio_path)

# Step 2: Create the video with the processed chant audio and background music
create_video_with_audio(image_path, processed_audio_path, input_bgm_audio_path, output_video_path)


Подробнее здесь: https://stackoverflow.com/questions/792 ... of-108-tim
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»