Sure! Creating a music rating program with the specifications you've provided is a multi-step process that involves downloading videos, processing audio, scraping data from a website, collecting user input, and generating a final video compilation. Below is a step-by-step guide along with code snippets to help you build this program in Python.
Prerequisites
Before we begin, make sure you have the following tools installed:
Step 1: Retrieve Playlist Information
First, we need to get all the video URLs from the playlist.
import yt_dlp
def get_playlist_videos(playlist_url):
ydl_opts = {
'quiet': True,
'extract_flat': True,
'skip_download': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(playlist_url, download=False)
video_urls = ['https://www.youtube.com/watch?v=' + entry['id'] for entry in info['entries']]
return video_urls
# Example usage
playlist_url = input("Enter the YouTube playlist URL: ")
video_urls = get_playlist_videos(playlist_url)
Step 2: Download Videos and Extract Loudest Segment
We'll download each video and extract the loudest x seconds.
import os
import subprocess
def download_and_process_video(video_url, duration):
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(title)s.%(ext)s',
'quiet': True,
}
if not os.path.exists('downloads'):
os.makedirs('downloads')
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(video_url, download=True)
video_title = info_dict.get('title', None)
filename = ydl.prepare_filename(info_dict)
base_filename = os.path.splitext(filename)[0]
loudest_clip = f"{base_filename}_loudest.wav"
# Use ffmpeg to find the loudest part
cmd = f"ffmpeg -hide_banner -loglevel error -i \"{filename}\" -af \"silencedetect=n=-50dB:d=0.5, adetect=s=0.05\" -f null -"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
_, stderr = process.communicate()
stderr = stderr.decode()
# Extract timestamps where the audio is loud
import re
matches = re.findall(r'silence_end: ([\d\.]+)', stderr)
timestamps = [float(match) for match in matches]
# Use the first loud segment or the middle of the song as fallback
if timestamps:
start_time = timestamps[0]
else:
start_time = duration / 2
# Ensure start_time is valid
start_time = max(0, start_time - duration / 2)
# Extract the loudest x seconds
output_filename = f"{base_filename}_clip.wav"
cmd = f"ffmpeg -hide_banner -loglevel error -ss {start_time} -t {duration} -i \"{filename}\" \"{output_filename}\""
subprocess.call(cmd, shell=True)
return output_filename, video_title
Step 3: Play the Audio Clip and Get User Rating
We can use pygame to play the audio clip.
import pygame
def play_audio_clip(filename):
pygame.mixer.init()
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue
pygame.mixer.quit()
def get_user_input(video_title, fetched_genres):
print(f"\nNow playing: {video_title}")
rating = int(input("Rate the song out of 100: "))
print(f"Fetched Genres: {', '.join(fetched_genres)}")
genres = input("Enter genres (comma-separated) or press Enter to accept fetched genres: ")
if genres.strip() == '':
genres = fetched_genres
else:
genres = [genre.strip() for genre in genres.split(',')]
comment = input("Enter an optional comment: ")
return rating, genres, comment
Step 4: Scrape Genres and Colors from NCS Wiki
We'll fetch genres from the NCS wiki.
import requests
from bs4 import BeautifulSoup
def fetch_genres(song_name, artist_name=None):
# Format the song name and artist for the URL
search_name = song_name.replace(' ', '_')
if artist_name:
search_name += f"_{artist_name.replace(' ', '_')}"
url = f"https://nocopyrightsounds.fandom.com/wiki/{search_name}"
response = requests.get(url)
genres = []
colors = []
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
# Find genres under "Community Genres" and "Subgenres"
genre_sections = soup.find_all('div', {'data-source': ['Community Genre', 'Subgenre']})
for section in genre_sections:
genre = section.find('div', class_='pi-data-value').get_text(strip=True)
genres.append(genre)
# Assuming the color is stored somewhere, extract it
# For this example, we'll assign a default color
colors.append('#FFFFFF') # White as default
else:
genres = ['Unknown']
colors = ['#FFFFFF']
return genres, colors
Step 5: Save Data to CSV
We'll collect all song data and save it to a CSV file.
import pandas as pd
def save_to_csv(song_data_list):
df = pd.DataFrame(song_data_list)
df = df.sort_values(by='Rating', ascending=True)
df.to_csv('song_ratings.csv', index=False)
# Example song data format
# song_data = {
# 'Title': 'Song Name',
# 'Rating': 85,
# 'Genres': ['Genre1', 'Genre2'],
# 'Colors': ['#FF0000', '#00FF00'],
# 'Comment': 'Great song!'
# }
Step 6: Generate the Final Video
We'll use moviepy to create a video compilation.
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip, concatenate_videoclips
def create_final_video(song_data_list):
clips = []
for data in song_data_list:
# Load the audio clip
audio_clip = AudioFileClip(data['ClipFilename'])
# Create a video clip with a solid color background
video_clip = ColorClip(size=(1280, 720), color=(0, 0, 0)).set_duration(audio_clip.duration)
video_clip = video_clip.set_audio(audio_clip)
# Create text clips for Title, Genres, and Comment
title_text = TextClip(data['Title'], fontsize=40, color='white').set_position('center')
title_text = title_text.set_start(audio_clip.duration * (1/3)).set_duration(audio_clip.duration * (2/3))
genre_texts = []
for genre, color in zip(data['Genres'], data['Colors']):
genre_text = TextClip(genre, fontsize=30, color=color).set_duration(video_clip.duration)
genre_texts.append(genre_text)
comment_text = TextClip(data['Comment'], fontsize=20, color='white').set_position(('center', 'bottom'))
comment_text = comment_text.set_duration(video_clip.duration)
# Composite all clips
composite = CompositeVideoClip([video_clip, title_text, comment_text] + genre_texts)
clips.append(composite)
final_clip = concatenate_videoclips(clips)
final_clip.write_videofile('final_ranking_video.mp4', fps=24)
Putting It All Together
Here's how we can bring all the steps into a cohesive program.
def main():
playlist_url = input("Enter the YouTube playlist URL: ")
duration = float(input("Enter the number of seconds to sample from each song: "))
video_urls = get_playlist_videos(playlist_url)
song_data_list = []
for url in video_urls:
clip_filename, video_title = download_and_process_video(url, duration)
# Optionally, extract artist name from the title
song_name, artist_name = parse_title(video_title)
fetched_genres, fetched_colors = fetch_genres(song_name, artist_name)
play_audio_clip(clip_filename)
rating, genres, comment = get_user_input(video_title, fetched_genres)
song_data = {
'Title': video_title,
'Rating': rating,
'Genres': genres,
'Colors': fetched_colors, # You might want to map genres to colors
'Comment': comment,
'ClipFilename': clip_filename
}
song_data_list.append(song_data)
save_to_csv(song_data_list)
create_final_video(song_data_list)
print("Final video created as 'final_ranking_video.mp4'.")
def parse_title(video_title):
# Implement parsing logic to extract song name and artist
# This is a placeholder implementation
parts = video_title.split(' - ')
if len(parts) >= 2:
artist_name = parts[0].strip()
song_name = parts[1].strip()
else:
artist_name = None
song_name = video_title
return song_name, artist_name
if __name__ == "__main__":
main()
Notes and Considerations
- Error Handling: Make sure to include error handling for network requests, file operations, and user inputs.
- Progress Indication: Provide feedback to the user during long operations like downloads and video processing.
- Genre Colors: Since colors are not directly available, you might need to maintain a mapping of genres to colors.
- User Adjustments: Before moving on, present fetched genres and allow the user to make adjustments.
- Duplicates Handling: Implement logic to handle duplicate song names by considering the artist name.
- Video Visibility: Ensure text overlays in the final video have outlines or shadows to be visible against any background.
- Dependencies: This program relies on external tools and libraries; ensure they are correctly installed and configured.
- Legal Considerations: Be mindful of YouTube's terms of service and any copyright laws when downloading and using content.
This should provide a solid foundation to create the program you described. Due to the complexity and length of the code, some parts are simplified and may need further development. Remember to test each part individually to ensure functionality before integrating everything together.
If you have any questions or need clarification on any part, feel free to ask!