async def downloadVideo(self): # Get Video var_video = YouTube(self.url) time.sleep(0.05) # Get Title from Video var_title = var_video.title time.sleep(0.05) # Select Stream var_stream = var_video.streams.order_by("bitrate").filter(only_audio=True, file_extension="mp4").last() # Store File in Variable var_File = var_stream.download(self.path) var_newFile, ext = os.path.splitext(var_File) # Convert File audio = AudioFileClip(os.path.abspath(var_File)) audio.write_audiofile(var_newFile + ".mp3") audio.close() os.remove(os.path.abspath(var_File)) # Get Metadata finalFile = eyed3.load(os.path.abspath(var_newFile + ".mp3")) finalFile.tag.artist = self.artist finalFile.tag.album = self.album finalFile.tag.title = var_title finalFile.tag.save() print("Finished Download and Converting of: " + var_title)
def convert(path): for root, folders, files in os.walk(path): for file_ in files: if not fnmatch.fnmatch(file_, '*.mp4'): continue complete_path = os.path.join(root, file_) filename, file_extension = os.path.splitext(complete_path) mp4_file = filename + '.mp4' mp3_file = filename + '.mp3' if not os.path.isfile(mp4_file): continue audio = AudioFileClip(mp4_file) audio.write_audiofile(mp3_file) audio.close() os.remove(mp4_file) # save_as = input('Save as: /home/yuukiasuna/') # destination = f'/home/yuukiasuna/{save_as}/' new_filename = mp3_file.split('/') destination = '/home/yuukiasuna/Downloads/Music/' shutil.move(mp3_file, destination + new_filename[-1])
class VideoBarrier(object): """docstring for VideoBarrier""" CLIP_DIR = "clip" def __init__(self, input, output, audio_path): super(VideoBarrier, self).__init__() self.input = input self.filename, _ = os.path.splitext(os.path.basename(input)) self.output = os.path.join(output, VideoBarrier.CLIP_DIR) self.audio_path = audio_path def __enter__(self): self.v_clip = VideoFileClip(self.input, audio=False) self.a_clip = AudioFileClip(self.audio_path) return self def __exit__(self, exception_type, exception_value, traceback): self.v_clip.close() self.a_clip.close() def set_audio(self, t_start=0, t_end=None): self.v_clip = self.v_clip.set_audio(self.a_clip.subclip( t_start, t_end)) def save(self, start_time=0, duration=60): audio_fname, _ = os.path.splitext(os.path.basename(self.audio_path)) output_fname = "{}_{}.mp4".format(self.filename, audio_fname) output_path = os.path.join(self.output, output_fname) self.v_clip.set_duration(duration + 1).subclip( t_start=start_time, t_end=start_time + duration).write_videofile(output_path)
def extract_mp3(video_file): path_ = "tracce_mp4//" + video_file audio_name = video_file[0:-3] + "mp3" clip = AudioFileClip(path_) clip.write_audiofile(audio_name) shutil.move(str(audio_name), audio_path) clip.close()
def divide_audio(audio_folder, num_parts, parts_folder, audio_part_prefix, lazy_update): get_subpart_path = lambda num_part: get_path( parts_folder, f"{audio_part_prefix}{num_parts}_part_", num_part, "mp3") if all( os.path.exists(get_subpart_path(i)) for i in range(1, num_parts + 1)) and lazy_update: print( f"All the divisions for {num_parts} num_parts already exist and lazy_update is set to True, so we are skipping this." ) return audio = AudioFileClip(audio_folder) total_duration = audio.duration part_duration = total_duration / num_parts for i in range(1, num_parts + 1): t_start, t_end = part_duration * (i - 1), part_duration * i #audio = None #need to create the object again because subclip updates audio_i = audio.coreader().subclip( t_start, t_end) #the coreader() creates a new copy, each one for each piece print(f"Trying to write part #{i}\n") print(f"audio goes from {t_start}s to {t_end}s\n") audio_i.write_audiofile(get_subpart_path(i)) #audio_i.close() print(f"Finished writing part #{i}") audio.close() print(f"Finish writing all parts in {parts_folder}")
def merge_audio_and_video(video_input_path, audio_input_path, video_output_path): """This function is used to mge voice with a video merged from images. Args: video_input_path: path of the origin video audio_input_path: path of the voice file video_output_path: path to the result video Returns: int on success this function returns 0 on failure this function returns 1 """ if not os.path.isfile(video_input_path): print("invalid video path") return FAILED if not os.path.isfile(audio_input_path): print("invalid audio path") return FAILED my_video_clip = VideoFileClip(video_input_path) my_audio_clip = AudioFileClip(audio_input_path) video = my_video_clip.set_audio(my_audio_clip) video.write_videofile(video_output_path, codec='libvpx') if not os.path.isfile(video_output_path): print("invalid output path") my_audio_clip.close() my_video_clip.close() return FAILED my_audio_clip.close() my_video_clip.close() return SUCCESS
def split(self, video_id: str, crop_start: float = 0, crop_end: float = 0): input_file_path = Path( self.input_path, "{vid}.{ext}".format(vid=video_id, ext=self.extension)) cropped_path = self.output_path / "{vid}.{ext}".format( vid=video_id, ext=self.extension) if input_file_path.exists(): # Audio if self.extension == "mp3" and self.should_crop(cropped_path): clip = AudioFileClip(str(input_file_path.absolute())) if crop_start is not 0 or crop_end is not 0: clip = clip.subclip(crop_start, crop_end) if clip.audio: clip.audio.write_audiofile(str(cropped_path.absolute())) clip.close() elif self.extension == "mp4" and self.should_crop(cropped_path): clip = VideoFileClip(str(input_file_path.absolute())) if crop_start is not 0 or crop_end is not 0: clip = clip.subclip(crop_start, crop_end) if clip: clip.write_videofile(str(cropped_path.absolute())) clip.close() else: # logger.warning('Failed to find file from: %s', input_file_path) pass
def __handle_download_all(self): """ Downloads all videos in the GUI video list to file location. This method creates a folder in the download location with all the audio files in the video list. The folder is in the format Youtube_Audio_Batch_Downloader_MM_DD_YYYY_hh_mm_ss """ folder_name = generate_folder() if not os.path.isdir(self.__values[Input.DOWNLOAD_LOCATION]): sg.Popup('Invalid path. Unable to download.') return download_path = os.path.join(self.__values[Input.DOWNLOAD_LOCATION], folder_name) num_videos = len(self.__loaded_videos) current_progress_bar = 0 progress_bar_iterator = ProgBar.MAX_VALUE.value / num_videos self.__window[Input.CURRENT_DOWNLOAD].update('Downloading: ') for video in self.__loaded_videos: title = self.__remove_special_char(video['title']) self.__window[Input.CURRENT_DOWNLOAD].update(f'Downloading: {video["title"]} ') video['audio'].download(download_path) video_file = download_path + f'\{title}.mp4' audio_file = download_path + f'\{title}.mp3' # Convert MP4 to MP3 file clip = AudioFileClip(video_file) clip.write_audiofile(audio_file) clip.close() os.remove(video_file) # Add thumbnail image to MP3 file response = urllib2.urlopen(video['thumbnail']) imagedata = response.read() audio = MP3(audio_file, ID3=ID3) audio.tags.add( APIC( encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=imagedata ) ) audio.save() self.__video_img.update(data=video['image']) self.__video_title.update(video['title']) self.__window[ProgBar.PROGRESS_BAR].update_bar(current_progress_bar + progress_bar_iterator) current_progress_bar += progress_bar_iterator self.__window[Input.CURRENT_DOWNLOAD].update('Download completed!') sg.Popup('Download Completed!')
def download(self, directory): bitrate = str(int(self.stream.bitrate / 1000)) + "k" url = self.stream.url extension = ".mp3" if self.onlyAudio else ".mp4" finalPath = os.path.join(directory, sanitizeFilename(self.name) + extension) clip = AudioFileClip(url) if self.onlyAudio else VideoFileClip(url) if self.stream.mediaType == "V": audioClip = AudioFileClip(self.audioStream.url) clip = clip.set_audio(audioClip) if self.volumeMultiplier != 0: newVolume = ( 1 + self.volumeMultiplier / 100 )**2 if self.volumeMultiplier < 0 else self.volumeMultiplier / 5 clip = clip.volumex(newVolume) if self.cut: # Clip the video low = self.lowCut high = self.highCut if low < 0: low = 0 if high > clip.end: high = clip.end clip = clip.subclip(low, high) # Save as final path name if self.onlyAudio: clip.write_audiofile(finalPath, bitrate=bitrate) self.applyID3Tags(finalPath) else: clip.write_videofile(finalPath, threads=NUM_THREADS) clip.close() elif self.onlyAudio: clip.write_audiofile(finalPath, bitrate=bitrate) clip.close() self.applyID3Tags(finalPath) else: clip.write_videofile(finalPath, threads=NUM_THREADS) clip.close() try: clip.close() except: pass return finalPath
def conversion(dir: str): """Combines a .png and .mp3 to create a .mp4 Args: dir (str): A directory that pictures, sounds, and movies directories are saved in Returns: None """ picture_dir = "{}/pictures".format(dir) sound_dir = "{}/sounds".format(dir) movie_dir = "{}/movies".format(dir) trash_list = get_baddies(dir) file_amount = 80 # added the title audio_clip = AudioFileClip("{}/.title.mp3".format(sound_dir)) audio_duration = audio_clip.duration + .20 audio_duration = datetime.datetime.utcfromtimestamp(audio_duration) audio_clip.close() duration_format = audio_duration.strftime("%H:%M:%S.%f") command = "ffmpeg -hide_banner -loglevel panic -loop 1 -y -i {}/.title.png -i {}/.title.mp3 -t {} {}/.title.mp4".format( picture_dir, sound_dir, duration_format, movie_dir, ) os.system(command) for number in tqdm(range(1, file_amount)): if str(number) in trash_list: continue audio_clip = AudioFileClip("{}/comment{}.mp3".format( sound_dir, number)) audio_duration = audio_clip.duration + .20 audio_duration = datetime.datetime.utcfromtimestamp(audio_duration) audio_clip.close() duration_format = audio_duration.strftime("%H:%M:%S.%f") command = "ffmpeg -hide_banner -loglevel panic -loop 1 -y -i {}/comment{}.png -i {}/comment{}.mp3 -t {} {}/comment{}.mp4".format( picture_dir, number, sound_dir, number, duration_format, movie_dir, number) os.system(command) print("Your files have been converted")
def write_audio_of_videos_in_parts(name, num_parts, video_folder="./videos/", audio_folder="./audios/", audio_prefix="audio_", lazy_update=True): all_parts_folder = f"{audio_folder}{name}/" get_subpart_path = lambda num_part: get_path( all_parts_folder, f"{audio_prefix}{num_parts}_part_", num_part, "mp3") os.makedirs(all_parts_folder, exist_ok=True) #creating necessary folder if necessary total_audio_path = get_path(all_parts_folder, audio_prefix, name, "mp3") if os.path.exists(total_audio_path) and lazy_update: print( f"The audio: {total_audio_path} already exists and lazy_update is set to {lazy_update}, so we are skipping this." ) else: print(get_subpart_path(1)) list_all_clips = [] all_elements = os.listdir(f"{video_folder}{name}/") only_mp4 = list( filter(lambda name: name.endswith(".mp4"), all_elements)) #only keeping the videos sorted_videos = sorted( only_mp4, key=extract_number_from_video ) # ordering with the number, not with the str rep # 'video_2' goes before 'video_10' print( f"Found {len(sorted_videos)} videos, now trying to combine all audios!\n" ) for sub_video in sorted_videos: print(".", end="") #just to keep track of where we are subclip = AudioFileClip(f"{video_folder}{name}/{sub_video}") list_all_clips.append(subclip) clips_combined = concatenate_audioclips(list_all_clips) print() print("Clips combined, now writing to {}".format(total_audio_path)) clips_combined.write_audiofile(total_audio_path) print(f"\nNow trying to divide the audio in {num_parts} parts \n" ) #TODO: check if the parts already exist divide_audio(total_audio_path, num_parts, all_parts_folder, audio_prefix, lazy_update) audio = AudioFileClip(total_audio_path) every_part_duration = (audio.duration) / num_parts audio.close() return every_part_duration
def startPreview(onlyAudio, url, cut, low, high, volume): clip = None if onlyAudio: clip = AudioFileClip(url) else: clip = VideoFileClip(url) if volume != 0: clip = clip.volumex(volume) if cut: clip = clip.subclip(low, high) print("PREVIEWING WITH MOVIEPY") clip.preview() clip.close() # See https://github.com/Zulko/moviepy/issues/575 pygame.quit()
def split_audio_from_video(video_input_path, audio_output_path): """This function is used to extract voice from a video. Args: video_input_path: path of the origin video audio_output_path: path to the voice file Returns: int on success this function returns 0 on failure this function returns 1 """ if not os.path.isfile(video_input_path): print("invalid video path") return FAILED my_audio_clip = AudioFileClip(video_input_path) my_audio_clip.write_audiofile(audio_output_path, codec='libvorbis') if not os.path.isfile(audio_output_path): print("invalid output path") my_audio_clip.close() return FAILED my_audio_clip.close() return SUCCESS
# Download Youtube file filters = yt_obj.streams.filter(only_audio=True) download_video(filters[0]) print("Video finish downloaded") # Convert to MP3 print("Converting to MP3 now....") audio_clip = AudioFileClip( f"{DOWNLOADED_VIDEO_FILE_PATH}/{args.filename or yt_obj.title}.mp4" ) audio_clip.write_audiofile( f"{DOWNLOADED_VIDEO_FILE_PATH}/{args.filename or yt_obj.title}.mp3" ) audio_clip.close() print("Finish converted.") else: # progressive=True mean that stream have both video & audio filters = yt_obj.streams.filter(progressive=True) download_video(filters.get_highest_resolution()) print("Video finish downloaded") except RegexMatchError as e: print("Unable to find the Youtube video.") print("Probably is a private video.") except Exception as e: print(e)