import gradio as gr import subprocess import yt_dlp as youtube_dl def stream_video(youtube_url, stream_key): # Extract the video and audio links from the YouTube URL ydl_opts = { 'format': 'bestvideo+bestaudio/best', 'quiet': True, } with youtube_dl.YoutubeDL(ydl_opts) as ydl: video_info = ydl.extract_info(youtube_url, download=False) video_format = ydl.extract_info(youtube_url, download=False)['formats'][0]['format_id'] video_url = ydl.extract_info(youtube_url, download=False)['url'] audio_format = ydl.extract_info(video_url, download=False)['formats'][0]['format_id'] audio_url = ydl.extract_info(video_url, download=False)['url'] # Build the ffmpeg command for video streaming video_cmd = f'ffmpeg -re -i "{video_url}" -c:v libx264 -preset veryfast -crf 22 -maxrate 4000k -bufsize 8000k -pix_fmt yuv420p -g 50 -c:a aac -b:a 192k -ac 2 -ar 44100 -f flv "rtmp://a.rtmp.youtube.com/live2/{stream_key}"' # Build the ffmpeg command for audio streaming audio_cmd = f'ffmpeg -re -i "{audio_url}" -vn -c:a aac -b:a 192k -ac 2 -ar 44100 -f flv "rtmp://a.rtmp.youtube.com/live2/{stream_key}"' # Start the video and audio streaming processes video_process = subprocess.Popen(video_cmd, shell=True) audio_process = subprocess.Popen(audio_cmd, shell=True) # Wait for the processes to finish video_process.wait() audio_process.wait() # Define the input and output interfaces for Gradio inputs = [ gr.inputs.Textbox(label="YouTube URL", default="https://www.youtube.com/watch?v=dQw4w9WgXcQ"), gr.inputs.Textbox(label="Stream Key", default="YOUR_STREAM_KEY"), ] outputs = gr.outputs.Textbox(label="Streaming Status") # Create the Gradio app and run it app = gr.Interface(fn=stream_video, inputs=inputs, outputs=outputs, title="YouTube Live Streaming with FFmpeg") app.launch()