0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

YouTubeリンクを入力すると、MP4 と MP3 を保存するためのコード

0
Last updated at Posted at 2025-12-04
!pip install pytube moviepy pydub
from pytube import YouTube
from moviepy.editor import AudioFileClip
import re

# ▼ URL補正(短縮URL対応 & ?si=削除)
def clean_url(url):
    if "youtu.be" in url:
        video_id = url.split("/")[-1].split("?")[0]
        return f"https://www.youtube.com/watch?v={video_id}"
    
    url = re.sub(r"&si=.*", "", url)
    url = re.sub(r"\?si=.*", "", url)
    return url


# ▼ MP4 ダウンロード
def download_mp4(url):
    yt = YouTube(url)
    stream = yt.streams.get_highest_resolution()
    stream.download(output_path=".", filename="video.mp4")
    print("MP4 保存完了:video.mp4")


# ▼ MP3 ダウンロード
def download_mp3(url):
    yt = YouTube(url)
    stream = yt.streams.filter(only_audio=True).first()
    audio_path = stream.download(filename="audio_temp.mp4")

    audio_clip = AudioFileClip(audio_path)
    audio_clip.write_audiofile("audio.mp3")
    audio_clip.close()

    print("MP3 保存完了:audio.mp3")


# ▼ メイン実行
url = input("YouTube URL を入力してください:")
url = clean_url(url)

download_mp4(url)
download_mp3(url)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?