Well, i was trying to make a program that you could download mp4 and mp3 files from youtube. The mp4 part is alright, but the mp3 part... ouch Since yesterday i was trying to do sometype of converting mechanism (i'm new to coding) that took the mp4 file that i downloaded and then convert it to mp3, after hours and hours i found way that could do it in a way that i can hear the audio (simply changing the .mp4 to .mp3 didnt work).
But theres a slight problem, after about 4 seconds of audio, it starts repeating itself, just like a scratched cd, and i have no ideia of how to fix it.
import os
from pytube import YouTube
from moviepy.editor import *
link = input("Coloque o link: ")
yt = YouTube(link)
def removespecialchars(string):
allowed_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-()[]{}\\:')
cleaned_string = ''.join(char for char in string if char in allowed_chars)
cleaned_string += ".mp3"
return cleaned_string
print("Title: ", yt.title)
print("Views: ", yt.views)
while True:
formatChoice = input("Você quer mp3 ou mp4? ").upper()
if formatChoice == "MP4":
youtubeDownloadMP4 = yt.streams.get_highest_resolution()
youtubeDownloadMP4.download("D:\\Videos\\YoutubeVideo")
print("Seu vídeo foi instalado")
break
elif formatChoice == "MP3":
youtubeDownloadMP3 = yt.streams.filter(only_audio=True).first()
caminho = ("D:\\Music")
mp3filename = removespecialchars(yt.title)
mp3path = os.path.join(caminho, mp3filename)
youtubeDownloadMP3.download(caminho, filename=mp3filename)
audioClip = AudioFileClip(mp3path)
audioClip.write_audiofile(mp3path, codec='libmp3lame')
print("Seu mp3 foi instalado")
break
else:
print("Escreva 'mp3' ou 'mp4' burro")
(something are in portuguese, dont worry bout it)
expecting it to work as normally, the mp3 file (already converted) started repeating about 4 secs
It's unclear why the audio crashes after the conversion according to your provided information. (Maybe it's an encoding/decoding issue?)
Instead of using moviepy
, you could try ffmpeg
, which may be more robust and can automatically determine which codec to use. In this case, just replace the following lines in your code:
audioClip = AudioFileClip(mp3path)
audioClip.write_audiofile(mp3path, codec='libmp3lame')
to this:
ffmpeg.input(mp3path).output(mp3path.replace('.mp3', '_convert.mp3')).run()
p.s. In order to make use of ffmpeg
in Python, you need to install it with pip install ffmpeg-python
and add import ffmpeg
at the beginning of your code.