File size: 1,096 Bytes
d9dfe6b
 
 
 
7fc59b1
 
d9dfe6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fc59b1
d9dfe6b
7fc59b1
 
d9dfe6b
7fc59b1
 
d9dfe6b
 
 
 
 
 
 
7fc59b1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import pytube
import os
from pytube import YouTube

def download_youtube_audio(youtube_url):
    """Downloads the audio from a YouTube video, renames it to the first twelve characters, and returns the downloaded file path."""

    try:
        # Create a YouTube object
        yt = YouTube(youtube_url)

        # Get the audio stream
        audio = yt.streams.filter(only_audio=True).first()

        # Download the audio
        print("Downloading...")
        audio.download()

        # Get the original filename
        original_filename = audio.default_filename

        # Extract the first twelve characters and change the file extension to .mp3
        new_filename = original_filename[:12] + '.mp3'

        # Rename the downloaded file
        os.rename(original_filename, new_filename)

        print("Download complete! Audio saved to:", new_filename)
        return new_filename

    except Exception as e:
        print("An error occurred:", e)
        return None

# Example usage
youtube_url = "https://www.youtube.com/watch?v=your_video_id"
download_youtube_audio(youtube_url)