def get_audio(self): created = False audio = Audio() self._audio_file = f'{self.filename}.mp3' clip = AudioFileClip(self._video_file) clip.write_audiofile(self._audio_file) clip.close() try: audio.mp3 = File(open(self._audio_file, mode='rb')) print('File was successfully uploaded.') audio.name = self._title audio.api = 'PyTube API' try: audio.save() except: print('Object was not saved!') created = True except Exception: print('File not found!') self._highlight_title() if created: return created, audio else: return created, None
class AudioStim(Stim): ''' Represents an audio clip. For now, only handles wav files. Args: filename (str): Path to audio file. onset (float): Optional onset of the audio file (in seconds) with respect to some more general context or timeline the user wishes to keep track of. sampling_rate (int): Sampling rate of clip, in hertz. ''' def __init__(self, filename=None, onset=None, sampling_rate=44100, url=None, clip=None): if url is not None: filename = url self.filename = filename self.sampling_rate = sampling_rate self.clip = clip if self.clip is None: self._load_clip() # Small default buffer isn't ideal, but moviepy has persistent issues # with some files otherwise; see # https://github.com/Zulko/moviepy/issues/246 self.data = self.clip.to_soundarray(buffersize=1000) duration = self.clip.duration if self.data.ndim > 1: # Average channels to make data mono self.data = self.data.mean(axis=1) super(AudioStim, self).__init__(filename, onset=onset, duration=duration) def _load_clip(self): self.clip = AudioFileClip(self.filename, fps=self.sampling_rate) def __getstate__(self): d = self.__dict__.copy() d['clip'] = None return d def __setstate__(self, d): self.__dict__ = d self._load_clip() @contextmanager def get_filename(self): if self.filename is None or not os.path.exists(self.filename): tf = tempfile.mktemp() + '.wav' self.clip.write_audiofile(tf) yield tf os.remove(tf) else: yield self.filename
def get_mp3(url): youtube_video = YouTube(url) title = special_characters(youtube_video.title) # Converting MP4 to MP3 mp3_file = f'{title}.mp3' mp4_file = f'{title}.mp4' youtube_video.streams.filter(only_audio=True).first().download() mp3_file_path = os.path.join(BASE_DIR, mp3_file) mp4_file_path = os.path.join(BASE_DIR, mp4_file) clip = AudioFileClip(mp4_file_path) clip.write_audiofile(mp3_file_path) clip.close() # os.remove(mp4_file_path) audio = Audio() audio.mp3 = File(open(mp3_file, mode='rb')) # audio.image = img audio.image = youtube_video.thumbnail_url audio.name = youtube_video.title audio.save() if mp4_file in os.listdir(BASE_DIR): os.remove(mp4_file) if mp3_file in os.listdir(BASE_DIR): os.remove(mp3_file)
def test_audio_coreader(): if sys.platform.startswith("win"): pytest.skip("Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error") sound = AudioFileClip("media/crunching.mp3") sound = sound.subclip(1, 4) sound2 = AudioFileClip("media/crunching.mp3") sound2.write_audiofile(os.path.join(TMP_DIR, "coreader.mp3"))
def test_audio_coreader(): if sys.platform.startswith("win"): pytest.skip( "Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error" ) sound = AudioFileClip("media/crunching.mp3") sound = sound.subclip(1, 4) sound2 = AudioFileClip("media/crunching.mp3") sound2.write_audiofile(os.path.join(TMP_DIR, "coreader.mp3"))
def convert(self, listFiles): # convert mp4 file to mp3 for file in listFiles: root, ext = os.path.splitext(file) if ext == '.mp4': mp4_path = os.path.join(self.pathFolder, file) mp3_path = os.path.join(self.pathFolder, root + '.mp3') new_file = AudioFileClip(mp4_path) new_file.write_audiofile(mp3_path) os.remove(mp4_path)
def cut_audio_from_video(self): """ a method to get the audio from a video and save it in the project folder and create a object of this @return: a audio object which contains the path """ folder = Path(self.folder_path, self.folder_name) audio_from_video = 'audio.mp3' audio = AudioFileClip(self.video_data) audio.write_audiofile(os.path.join(folder, audio_from_video), verbose=False, logger=None) extracted_audio = Path(folder, audio_from_video) self.audio_files.append(extracted_audio) return Audio(extracted_audio)
def write_mp3_files(filename_translated, voice_id): translated_subs = pysrt.open(filename_translated, encoding='utf-8') for index, each in enumerate(translated_subs): subtitle_index = index + 1 content = each.text print(subtitle_index) print(content) time_duration = each.duration time_duration_milliseconds = get_milli_seconds(time_duration) # Add some buffer to time duration just to accomodate beginning and end time_duration_milliseconds = time_duration_milliseconds + 250 time_duration_string = str(time_duration_milliseconds) + "ms" s = AmazonSpeech() s.max_duration(time_duration_string, content) text = s.ssml() del s response = polly.synthesize_speech( OutputFormat='mp3', Text=text, TextType='ssml', VoiceId=voice_id, ) # Voices https://docs.aws.amazon.com/polly/latest/dg/voicelist.html body = response['AudioStream'].read() append_string = '__' + str(subtitle_index) + '.mp3' mp3filename = filename_translated.replace('.srt', append_string) wavfilename = mp3filename.replace('.mp3', '.wav') with open(mp3filename, 'wb') as file: file.write(body) file.close() translated_wavfilename = AudioFileClip(mp3filename) translated_wavfilename.write_audiofile(wavfilename, ffmpeg_params=['-ac', '1']) os.remove(mp3filename)
def download_audio(self, vid, qual, target_dir, ind, n): if qual == "Highest": path = vid.streams.get_audio_only( subtype="webm").download(target_dir) for stream in vid.streams: if stream.mime_type == "audio/webm" and stream.abr == qual: path = stream.download(target_dir) break else: path = vid.streams.get_audio_only( subtype="webm").download(target_dir) new_path = path[:-5] + ".mp3" file = AudioFileClip(path) self.message_label.setText( f"Converting audio stream to mp3.. ({ind + 1} of {n})") file.write_audiofile(new_path) file.close() os.remove(path) metadata = vid.metadata.metadata f = music_tag.load_file(new_path) f['artist'] = (metadata[0]['Artist'] if len(metadata) > 0 and metadata[0].get('Artist') is not None else vid.author) f['comment'] = vid.description f['compilation'] = False f['composer'] = f['artist'] f['tracktitle'] = (metadata[0]['Song'] if len(metadata) > 0 and metadata[0].get('Song') is not None else vid.title) f['year'] = vid.publish_date.year f.save() return new_path
def test_audio_coreader(): sound = AudioFileClip("media/crunching.mp3") sound = sound.subclip(1, 4) sound2 = AudioFileClip("media/crunching.mp3") sound2.write_audiofile(os.path.join(TMP_DIR, "coreader.mp3"))
class AudioStim(Stim): ''' Represents an audio clip. Args: filename (str): Path to audio file. onset (float): Optional onset of the audio file (in seconds) with respect to some more general context or timeline the user wishes to keep track of. sampling_rate (int): Sampling rate of clip, in hertz. url (str): Optional url to read contents from. clip (AudioFileClip): Optional moviepy AudioFileClip to initialize from. order (int): Optional sequential index of the AudioStim within some containing context. ''' _default_file_extension = '.wav' def __init__(self, filename=None, onset=None, sampling_rate=None, url=None, clip=None, order=None): if url is not None: filename = url self.filename = filename if clip: self.sampling_rate = clip.fps self.clip = clip else: self.sampling_rate = sampling_rate if not self.sampling_rate: self.sampling_rate = self.get_sampling_rate(self.filename) self._load_clip() # Small default buffer isn't ideal, but moviepy has persistent issues # with some files otherwise; see # https://github.com/Zulko/moviepy/issues/246 self.data = self.clip.to_soundarray(buffersize=1000) duration = self.clip.duration if self.data.ndim > 1: # Average channels to make data mono self.data = self.data.mean(axis=1) super(AudioStim, self).__init__(filename, onset=onset, duration=duration, order=order, url=url) def _load_clip(self): self.clip = AudioFileClip(self.filename, fps=self.sampling_rate) @staticmethod def get_sampling_rate(filename): ''' Use moviepy/FFMPEG to get the sampling rate ''' infos = ffmpeg_parse_infos(filename) fps = infos.get('audio_fps', 44100) if fps == 'unknown': fps = 44100 return fps def __getstate__(self): d = self.__dict__.copy() d['clip'] = None return d def __setstate__(self, d): self.__dict__ = d self._load_clip() def save(self, path): ''' Save clip data to file. Args: path (str): Filename to save audio data to. ''' self.clip.write_audiofile(path, fps=self.sampling_rate)
class AudioStim(Stim): ''' Represents an audio clip. Args: filename (str): Path to audio file. onset (float): Optional onset of the audio file (in seconds) with respect to some more general context or timeline the user wishes to keep track of. sampling_rate (int): Sampling rate of clip, in hertz. ''' _default_file_extension = '.wav' def __init__(self, filename=None, onset=None, sampling_rate=None, url=None, clip=None): if url is not None: filename = url self.filename = filename self.sampling_rate = sampling_rate if not self.sampling_rate: self.sampling_rate = self.get_sampling_rate(self.filename) self.clip = clip if not self.clip: self._load_clip() # Small default buffer isn't ideal, but moviepy has persistent issues # with some files otherwise; see # https://github.com/Zulko/moviepy/issues/246 self.data = self.clip.to_soundarray(buffersize=1000) duration = self.clip.duration if self.data.ndim > 1: # Average channels to make data mono self.data = self.data.mean(axis=1) super(AudioStim, self).__init__(filename, onset=onset, duration=duration) @staticmethod def get_sampling_rate(filename): ''' Use FFMPEG to get the sampling rate, most of this code was adapted from the moviepy codebase ''' cmd = ['ffmpeg', '-i', filename] with open(os.devnull, 'rb') as devnull: creationflags = 0x08000000 if os.name == 'nt' else 0 p = subprocess.Popen(cmd, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags) _, p_err = p.communicate() del p lines = p_err.decode('utf8').splitlines() if 'No such file or directory' in lines[-1]: raise IOError(('Error: the file %s could not be found.\n' 'Please check that you entered the correct ' 'path.') % filename) lines_audio = [l for l in lines if ' Audio: ' in l] if lines_audio: line = lines_audio[0] try: match = re.search(' [0-9]* Hz', line) return int(line[match.start() + 1:match.end() - 3]) except: pass # Return a sensible default return 44100 def _load_clip(self): self.clip = AudioFileClip(self.filename, fps=self.sampling_rate) def __getstate__(self): d = self.__dict__.copy() d['clip'] = None return d def __setstate__(self, d): self.__dict__ = d self._load_clip() def save(self, path): self.clip.write_audiofile(path, fps=self.sampling_rate)
def convert(self, dir): '''Convert to the right format.''' music = AudioFileClip("temp\\" + self.display) music.write_audiofile("{}\\{}.mp3".format(dir, self.title))
class AudioStim(Stim): ''' Represents an audio clip. Args: filename (str): Path to audio file. onset (float): Optional onset of the audio file (in seconds) with respect to some more general context or timeline the user wishes to keep track of. sampling_rate (int): Sampling rate of clip, in hertz. url (str): Optional url to read contents from. clip (AudioFileClip): Optional moviepy AudioFileClip to initialize from. order (int): Optional sequential index of the AudioStim within some containing context. ''' _default_file_extension = '.wav' def __init__(self, filename=None, onset=None, sampling_rate=None, url=None, clip=None, order=None): if url is not None: filename = url self.filename = filename if clip: self.sampling_rate = clip.fps self.clip = clip else: self.sampling_rate = sampling_rate if not self.sampling_rate: self.sampling_rate = self.get_sampling_rate(self.filename) self._load_clip() # Small default buffer isn't ideal, but moviepy has persistent issues # with some files otherwise; see # https://github.com/Zulko/moviepy/issues/246 self.data = self.clip.to_soundarray(buffersize=1000) duration = self.clip.duration if self.data.ndim > 1: # Average channels to make data mono self.data = self.data.mean(axis=1) super(AudioStim, self).__init__( filename, onset=onset, duration=duration, order=order, url=url) def _load_clip(self): self.clip = AudioFileClip(self.filename, fps=self.sampling_rate) @staticmethod def get_sampling_rate(filename): ''' Use moviepy/FFMPEG to get the sampling rate ''' infos = ffmpeg_parse_infos(filename) fps = infos.get('audio_fps', 44100) if fps == 'unknown': fps = 44100 return fps def __getstate__(self): d = self.__dict__.copy() d['clip'] = None return d def __setstate__(self, d): self.__dict__ = d self._load_clip() def save(self, path): ''' Save clip data to file. Args: path (str): Filename to save audio data to. ''' self.clip.write_audiofile(path, fps=self.sampling_rate)
def mp3_converter(title, url): mp3_object = Audio() created = False mp3_id = None special_characters_flag = False file_name = title print('flag 3') print('flag 4') # Updating the title to compare it with the mp4 file that exist for it in this folder... title = special_characters(title) print('flag 5') mp3_file = f'{title}.mp3' mp4_file = f'{title}.mp4' # Converting MP4 to MP3 clip = AudioFileClip(mp4_file) clip.write_audiofile(mp3_file) clip.close() print('flag 6') try: # Opening the mp3 file to create an object to store to the database. mp3_object.mp3 = File(open(mp3_file, mode='rb')) mp3_object.name = file_name mp3_object.save() mp3_id = mp3_object.pk print('flag 7') # Deleting the downloaded file after uploading it to cloudinary here... if mp4_file in os.listdir(BASE_DIR): os.remove(mp4_file) if mp3_file in os.listdir(BASE_DIR): os.remove(mp3_file) created = True print('flag 8') except Exception: print("MP4 file cannot open properly") # Saving the object to the database. if not created: # Information that the object wasn't created successfully. We will use this value within the view.py to prevent # the programme from crashing. special_characters_flag = True # Now creating an object to inform administrator what to try and fix to improve the website's functionalities. error = TitleError() error.name = file_name error.url = str(url) error.email_sender() error.save() print('flag 9') print('flag 10') return mp3_id, special_characters_flag
def getYou(url, bot, chat_id, formato): temp_dir = tempfile.mkdtemp() if (formato == '.mp4'): try: yt = pytube.YouTube(url).streams.filter( res="720p").first().download(temp_dir) except: yt = pytube.YouTube(url).streams.filter( res="360p").first().download(temp_dir) video = glob.glob(temp_dir + '/*.mp4') final_path = '' ytPath = [] for i in video: final_path = i size = os.path.getsize(i) / 1000000 break if (size > 49.9999): video = VideoFileClip(final_path) duration = int(video.duration) start_time = 0 end_time = 600 parts = int(duration / 600) videopart = int(duration / 600) + 1 if (parts > (video.duration / 600)): parts = parts - 1 if (duration <= 630): subvideo = video.subclip(0, duration) bot.send_message(chat_id=chat_id, text='Finalizando ' + runner, timeout=60) subvideo.write_videofile(temp_dir + '/youtube' + '01' + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset='veryfast', fps=30, bitrate='520k') ytPath = temp_dir + '/youtube' + '01' + '.mp4' bot.send_video(chat_id=chat_id, video=open(ytPath, 'rb'), timeout=3600) shutil.rmtree(temp_dir) return ytPath elif (duration > 630): if (duration % 600 == 0): c = 1 for i in range(parts): if (end_time > duration): break subvideo = video.subclip(start_time, end_time) bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) c += 1 subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset='veryfast', fps=30, bitrate='550k') bot.send_video(chat_id=chat_id, video=open( temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', 'rb'), timeout=3600) start_time += 600.00 end_time += 600.00 elif (duration % 600 > 0): i = 0 c = 1 end_custom = (600 * parts) + (duration % 600) while i < parts: subvideo = video.subclip(start_time, end_time) bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset='veryfast', fps=30, bitrate='550k') bot.send_video(chat_id=chat_id, video=open( temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', 'rb'), timeout=3600) start_time += 600.00 end_time += 600.00 i += 1 c += 1 if (i == parts): subvideo = video.subclip(start_time, end_custom) bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset='veryfast', fps=30, bitrate='550k') time.sleep(1) bot.send_video(chat_id=chat_id, video=open( temp_dir + '/youtube' + '0' + str(i + 1) + '.mp4', 'rb'), timeout=3600) ytPath = glob.glob(temp_dir + '/*.mp4') shutil.rmtree(temp_dir) return ytPath else: bot.send_video(chat_id=chat_id, video=open(final_path, 'rb'), timeout=3600) shutil.rmtree(temp_dir) return final_path ############################## Get MP3 ################################################# elif formato == '.mp3': yt = pytube.YouTube(url).streams.filter( only_audio=True).first().download(temp_dir) video = glob.glob(temp_dir + '/*.mp4') for i in video: final_path = i break clip = AudioFileClip(final_path) audio_path = final_path.replace('mp4', 'mp3') clip.write_audiofile(audio_path, logger=None) bot.send_audio(chat_id=chat_id, audio=open(audio_path, 'rb'), timeout=3600) shutil.rmtree(temp_dir) return final_path