Youtube to wav

프로필

2024-12-20

306 0

Reason for development

I record as a hobby and sometimes I need an official sound source. In that case, I usually use the sites that support youtube to wav on the Internet, but some of the sites I have been using for quite a while have recently started to stop working, some of them are phishing sites, some of them allow downloading but add unnecessary spaces at the end of the music file, and some of them have restrictions such as limiting the number of songs that can be downloaded unless you don't donate.

If you're frustrated, you can run.

I decided to create my own.

Development Process

Python has a lot of libraries that make you say, "Oh my god, there's a library for that?", and the ones I used were pydub and yt-dlp.
Initially, I used pytube and moviepy, but pytube has been slow to update lately,

에러 발생: HTTP Error 403: Forbidden

and moviepy kept emitting

에러 발생: HTTP Error 403: Forbidden

and I don't know why, but it kept failing to import in the poetry virtual environment.

Traceback (most recent call last):
  File "/Users/-/Desktop/Youtube-to-wav/app/main.py", line 2, in <module>
    from moviepy.editor import AudioFileClip
ModuleNotFoundError: No module named 'moviepy.editor'

I tried checking with poetry show, uninstalling poetry and reinstalling it, but the module not found error persisted, so I ended up using pydub and yt-dlp.

The finalized code looks like this

import os

from pydub import AudioSegment
from yt_dlp import YoutubeDL


def download_youtube_audio(url, output_path="downloads"):
    try:
        if not os.path.exists(output_path):
            os.makedirs(output_path)

        ydl_opts = {
            "format": "bestaudio/best",
            "outtmpl": os.path.join(output_path, "%(title)s.%(ext)s"),
            "postprocessors": [
                {
                    "key": "FFmpegExtractAudio",
                    "preferredcodec": "wav",
                }
            ],
        }

        with YoutubeDL(ydl_opts) as ydl:
            print("다운로드 시작...")
            info = ydl.extract_info(url, download=True)
            print(f"다운로드 완료: {info['title']}")

            wav_path = os.path.join(output_path, f"{info['title']}.wav")
            print(f"변환 완료: {wav_path}")
            return wav_path

    except Exception as e:
        print(f"에러 발생: {str(e)}")
        return None


if __name__ == "__main__":
    url = input("YouTube URL을 입력하세요: ")
    download_youtube_audio(url)

I usually do my recording work on Windows, so I cloned it, installed ffmpeg, and tested it, and it worked fine.

However, on a MAC environment, you need to use homebrew to install the

brew install ffmpeg

On Windows, I had to go to the ffmpeg website, download it, rename the folder, move it to my C drive, and set the environment variables.

But now, with this code, I can get YouTube music as wav files when I want it, without ads, without reactions, and without the stress of sponsorship.

GIT repository address.

github.

#파이썬 #토이프로젝트

Comments 0

Login required to write comments