Search code examples
python-3.xformatpytube

PyTube downloads audio file in mp4 format. How to fix?


Good Afternoon. I'm beginner in python. So, I was trying to make YouTube Video/Audio Downloader with PyTube (For Educational Purpose only). I have seen many videos on youtube and I was trying to make this tool better. So I have added video/audio choosing option and resulation/quality choosing option. The Good thing is I have successfully made Video downloader. But I got a problem in the Audio Downloader. The problem is, PyTube downloads the audio file in MP4 format. I have searched on google and youtube. But I could not find any solution. I want to rename the from mp4 to mp3 (cause the file is OK, but the format is wrong). as a beginner, I don't know how to save a downloading file in somewhere else (temporary folder), and rename it then transfer it to output folder. I tried to add filename=link.title+'mp3'. But It returns this error: OSError: [Errno 22] Invalid argument: 'G:/Downloaded Videos/Latest English Ringtone | Turkish Bgm Ringtone 2021 | Bad Boy | Attitude Tone | Villain Ringtone.mp3'
here is my Code:

from pytube import YouTube
link='https://www.youtube.com/watch?v=KrhPrPK2owA'
link=YouTube(link)
print('Title:',link.title+'\n'+'Views:',link.views)
streams=link.streams.filter(type='audio')
kbps_list=[]
itag_list=[]
print('Available Kbps: ',end='')
for s in streams:
    i=s.itag
    s=s.abr
    if s not in kbps_list:
        kbps_list.append(s)
        itag_list.append(i)
        print(s,end=' ')
reso=input('\nEnter Kbps to download: ')
if reso not in kbps_list:
    print('This Kbps is not available')
    from sys import exit
    exit()
reso=kbps_list.index(reso)
final=streams.get_by_itag(itag_list[reso])
print('Downloading...')
final.download('G:/Downloaded Videos/')
# final.download('G:/Downloaded Videos/', filename=link.title+'mp3')======================
# if I add custom filename, It returns the error ========================================
print('Successfully Downloaded!')

Solution

  • Need to set the file name and can download in mp3 as you tried but it will still be in the mp4a codec. Not sure if that matters to you. Your title is all weird and it includes the file path. Probably why link.title is not working. Try the below code to strip the title and the file path.

    import os
    
    head tail = os.path.split(link.title)
    final=streams.get_by_itag(itag_list[reso]).download(filename=tail.strip(" | ") + ".mp3")
    

    You can also set output directory by passing the argument output_path="some location".

    It would look like:

    final=streams.get_by_itag(itag_list[reso]).download(output_path="some location", filename=tail.strip(" | ") + ".mp3")