Created
August 6, 2023 02:13
-
-
Save JupyterJones/675d904b943c3d6cf5218e63676c58ce to your computer and use it in GitHub Desktop.
Gets a random song from an mp3 directory. gets a random 58 seconds from that mp3 and save with a unique using uuid as an .mp3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from moviepy.editor import AudioFileClip | |
import random | |
from scipy.io import wavfile | |
import uuid | |
import glob | |
import random | |
# Function to find a random song in the Music directory | |
def music(): | |
MUSIC = random.choice(glob.glob("/home/jack/Desktop/HDD500/collections/Music/*.mp3")) | |
return MUSIC | |
audio_clip = AudioFileClip(music()) # Replace with your audio file path | |
# Define fade durations | |
fade_in_duration = 10 # seconds | |
fade_out_duration = 10 # seconds | |
# Calculate the maximum possible start time to ensure the selected section fits within the audio clip | |
max_start_time = audio_clip.duration - (58 - fade_in_duration - fade_out_duration) | |
# Choose a random start time within the valid range | |
random_start_time = random.uniform(0, max_start_time) | |
# Calculate the end time based on the random start time and desired total duration | |
random_end_time = random_start_time + (58 - fade_out_duration) | |
# Extract the random section from the audio clip | |
random_section = audio_clip.subclip(random_start_time, random_end_time) | |
# Apply fade-in and fade-out effects | |
faded_audio = random_section.audio_fadein(fade_in_duration).audio_fadeout(fade_out_duration) | |
# Make sure the resulting audio clip is exactly 58 seconds long | |
final_audio_clip = faded_audio.subclip(0, 58) | |
# Print the duration of the final audio clip | |
print("Final audio clip duration:", final_audio_clip.duration, "seconds") | |
# Preview the final audio clip | |
final_audio_clip.preview() | |
base_filename = str(uuid.uuid4()) | |
# Save the audio as a WAV file | |
clip=final_audio_clip | |
wavfile.write("zooms/"+base_filename+".wav", int(clip.fps), clip.to_soundarray()) | |
import subprocess | |
# Convert the WAV file to MP3 using FFmpeg | |
subprocess.run(["ffmpeg", "-i", "zooms/"+base_filename+".wav", "zooms/"+base_filename+".mp3"]) | |
print("Audio saved as zooms/"+base_filename+".wav") | |
clip.preview() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment