| import yt_dlp | |
| import os | |
| def download_audio(video_url, output_dir="./data/audio"): | |
| os.makedirs(output_dir, exist_ok=True) | |
| ydl_opts = { | |
| 'format': 'bestaudio/best', | |
| 'outtmpl': f'{output_dir}/%(id)s.%(ext)s', | |
| 'postprocessors': [{ | |
| 'key': 'FFmpegExtractAudio', | |
| 'preferredcodec': 'mp3', | |
| 'preferredquality': '192', | |
| }], | |
| 'quiet': True, | |
| } | |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
| info = ydl.extract_info(video_url, download=True) | |
| audio_path = os.path.join(output_dir, f"{info['id']}.mp3") | |
| return audio_path | |