| import gradio as gr |
| import yt_dlp as youtube_dl |
| from pydub import AudioSegment |
| from pydub.playback import play |
| import os |
| import tempfile |
|
|
| |
| def download_and_convert(url): |
| ydl_opts = { |
| 'format': 'bestaudio/best', |
| 'outtmpl': '%(title)s.%(ext)s', |
| 'noplaylist': True, |
| 'quiet': True, |
| 'http_headers': { |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' |
| } |
| } |
| |
| try: |
| with youtube_dl.YoutubeDL(ydl_opts) as ydl: |
| info = ydl.extract_info(url, download=True) |
| video_title = info['title'] |
| video_ext = info['ext'] |
| |
| |
| temp_dir = tempfile.mkdtemp() |
| video_path = os.path.join(temp_dir, f"{video_title}.{video_ext}") |
| audio_path = os.path.join(temp_dir, f"{video_title}.aac") |
| |
| |
| if not os.path.exists(video_path): |
| return None, temp_dir |
| |
| |
| video = AudioSegment.from_file(video_path) |
| video.export(audio_path, format='aac') |
| |
| |
| os.remove(video_path) |
| |
| return audio_path, temp_dir |
| except Exception as e: |
| return str(e), None |
|
|
| |
| def play_audio_and_prepare_next(urls): |
| if not urls: |
| return "Nenhuma URL fornecida." |
| |
| urls = urls.split('\n') |
| audio_paths = [] |
| temp_dirs = [] |
|
|
| for url in urls: |
| audio_path, temp_dir = download_and_convert(url) |
| |
| if audio_path is None: |
| return f"Erro ao baixar o vídeo: {url}" |
| |
| if isinstance(audio_path, str) and "ERROR" in audio_path: |
| return audio_path |
| |
| audio_paths.append(audio_path) |
| temp_dirs.append(temp_dir) |
| |
| |
| for audio_path, temp_dir in zip(audio_paths, temp_dirs): |
| audio = AudioSegment.from_file(audio_path) |
| play(audio) |
| |
| |
| os.remove(audio_path) |
| os.rmdir(temp_dir) |
|
|
| return "Reprodução concluída." |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("### YouTube Audio Player") |
| url_input = gr.Textbox(placeholder="Cole a URL do vídeo ou playlist do YouTube aqui...") |
| play_button = gr.Button("Tocar") |
| output = gr.Textbox() |
|
|
| play_button.click(play_audio_and_prepare_next, inputs=url_input, outputs=output) |
|
|
| |
| demo.launch() |
|
|