コード例 #1
0
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])
コード例 #2
0
 def Audio_Visual_Separation(self,
                             Video_Path,
                             Video_Name,
                             Audio_Path=None,
                             Audio_Name=None):
     """
     音频分离函数
     首先检查地址是否存在,默认只需要视频地址和视频名称,音频默认存放之视频地址下
     视频是MP4格式,音频默认是MP3格式
     :param Video_Path:视频地址
     :param Video_Name: 视频名
     :param Audio_Path: 音频地址
     :param Audio_Name: 音频名称
     :return: 分离好的音频
     """
     self.Video_Path = Video_Path
     self.Video_Name = Video_Name
     if Audio_Path is not None:
         self.Audio_Path = Audio_Path
     else:
         self.Audio_Path = Video_Path
     if Audio_Name is not None:
         self.Audio_Name = Audio_Name
     else:
         self.Audio_Name = Video_Name.replace(".mp4", ".mp3")
     if self._path_check(self.Video_Path + self.Video_Name):
         if self._path_check(self.Audio_Path):
             __video_path = self.Video_Path + self.Video_Name
             __audio_path = self.Audio_Path + self.Audio_Name
             my_audio_clip = AudioFileClip(__video_path)
             my_audio_clip.write_audiofile(__audio_path)
         else:
             print('error! :audio file path cant find')
     else:
         print('error! :video file or file path cant find')
コード例 #3
0
ファイル: music.py プロジェクト: edoardo8uni/mp_-downloader
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()
コード例 #4
0
 def record_button_clicked(self, widget, mode):
     audio_jack = AudioJack.get_thread()
     if mode == "start":
         if self.record_filename is None:
             filename = FileOp.choose_file(self, purpose="save_as", file_types="audio")
             if filename:
                 self.set_record_filename(filename)
                 self.record_clock.reset()
         else:
             self.record_pause_button.show()
             self.record_stop_button.show()
             self.record_start_button.hide()
             audio_jack.record = True
             self.record_clock.start()
     elif mode == "pause":
         self.record_pause_button.hide()
         self.record_stop_button.show()
         self.record_start_button.show()
         audio_jack.record = False
         self.record_clock.pause()
     elif mode == "stop":
         self.record_pause_button.hide()
         self.record_start_button.show()
         self.record_stop_button.hide()
         audio_jack.record = False
         self.record_clock.pause()
         if self.record_filename:
             mid_filename = self.record_filename + ".{0}.wav".format(time.time())
             if audio_jack.save_record_file_as(mid_filename):
                 clip = AudioFileClip(mid_filename)
                 clip.write_audiofile(self.record_filename)
                 os.remove(mid_filename)
                 self.load_audio_samples(self.record_filename)
                 self.set_filename(self.record_filename)
         self.set_record_filename("")
コード例 #5
0
def separate_audio(file_path, save_path):
    audio_file = save_path + '\\tmp.wav'
    audio = AudioFileClip(file_path)
    audio.write_audiofile(audio_file,
                          ffmpeg_params=['-ar', '16000', '-ac', '1'],
                          logger=None)
    return audio_file
コード例 #6
0
    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)
コード例 #7
0
    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
コード例 #8
0
def extract_sound_from_video(video_path): #[s3_key]_[randomized_file_name]
  print('Extracting sound from video ['+video_path+']')
  # ./[input_name]_[random_string].[file_extension] -> ./[input_name]_[random_string].mp3
  tmp_extracted_sound_path = './'+os.path.basename(video_path).split('.')[0]+'.mp3'
  audio = AudioFileClip(video_path)
  audio.write_audiofile(tmp_extracted_sound_path)
  print('Sound extracted and saved under ['+tmp_extracted_sound_path+']')
  return tmp_extracted_sound_path
コード例 #9
0
ファイル: stt.py プロジェクト: yeonghoey/hew
def convert_to_wav(source_path):
    clip = AudioFileClip(source_path)
    wav_path = tempfile_path('.wav')
    # NOTE: -ac stands for 'audio channels'
    # Force mono since Google Cloud STT only accepts mono audio
    ffmpeg_params = ['-ac', '1']
    clip.write_audiofile(wav_path, ffmpeg_params=ffmpeg_params)
    return wav_path
コード例 #10
0
def main():
    file_name = '/home/uscc/USAI_Outsourcing/SBIR_fight_videos/ced_info_SBIR.csv'
    output_file1 = 'ucfInfo/ced_training.csv'
    output_file2 = 'ucfInfo/ced_testing.csv'
    v_ext = '.mp4'
    a_ext = '.mp3'

    subclips_info = pd.read_csv(file_name)

    # if os.path.exists(output_file1):
    #     csv_writer = csv.writer(open(output_file1, 'a'))
    # else:
    #     csv_writer = csv.writer(open(output_file1, 'w'))
    #     csv_writer.writerow(['name', 'label', 'score'])

    # if os.path.exists(output_file2):
    #     csv_writer2 = csv.writer(open(output_file2, 'a'))
    # else:
    #     csv_writer2 = csv.writer(open(output_file2, 'w'))
    #     csv_writer2.writerow(['name', 'label', 'score'])

    for index, row in subclips_info.iterrows():
        # if index < 316:
        #     continue
        print('[{}/{}] {}'.format(index, len(subclips_info), row.Name))
        # print('Name: {row.Name}\t'
        #       'Label: {row.label}\t'
        #       'start: {row.start}\t'
        #       'end: {row.end}\t'
        #       'score: {row.score}'.format(row=row))
        video_name = row.Name + v_ext
        audio_name = row.Name + a_ext
        output_name = row.Name[:-11] + 'v{:04d}_{}_{:03d}_n'.format(
            index, row.label, row.score)

        # if random() < 0.9:
        #     csv_writer.writerow([output_name, row.label, row.score])
        # else:
        #     csv_writer2.writerow([output_name, row.label, row.score])

        ## cut vedio and audio
        vedio_clip = VideoFileClip(video_name).subclip(row.start, row.end)
        audio_clip = AudioFileClip(audio_name).subclip(row.start, row.end)

        vedio_clip.write_videofile(output_name + v_ext)
        audio_clip.write_audiofile(output_name + a_ext)

        ## replace origional file
        os.remove(row.Name + v_ext)
        os.remove(row.Name + a_ext)
        os.rename(
            row.Name[:-11] +
            'v{:04d}_{}_{:03d}_n'.format(index, row.label, row.score) + v_ext,
            row.Name[:-11] + row.Name[50:-12] + v_ext)
        os.rename(
            row.Name[:-11] +
            'v{:04d}_{}_{:03d}_n'.format(index, row.label, row.score) + a_ext,
            row.Name[:-11] + row.Name[50:-12] + a_ext)
コード例 #11
0
    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!')
コード例 #12
0
ファイル: core.py プロジェクト: yeonghoey/hew
def main_path(source_path, download_yt_captions, convert_wav):
    if convert_wav:
        src = AudioFileClip(source_path)
        filename = os.path.basename(source_path)
        name, _ = os.path.splitext(filename)
        wav_path = os.path.join(tempdir_path(), name + '.wav')
        src.write_audiofile(wav_path)
        return wav_path
    else:
        return source_path
コード例 #13
0
ファイル: messenger.py プロジェクト: AmienKhaled/zoldyck
    def covertMp4Towav(self, inputName, outputName):
        """convert mp4 file to wave
        
        Arguments:
            inputName {string} -- file name
            outputName {string} -- file name after converting
        """

        audioclip = AudioFileClip(inputName)
        audioclip.write_audiofile(outputName)
コード例 #14
0
def generate_fingerprint(fname: str) -> List[int]:
    """return an audio fingerprint for a video file.
    """
    audioclip = AudioFileClip(fname)
    audioclip.write_audiofile("temp.wav")

    duration, fp_encoded = acoustid.fingerprint_file("temp.wav")
    fingerprint, version = decode_fingerprint(fp_encoded)

    os.remove("temp.wav")
    return fingerprint
コード例 #15
0
ファイル: mp3.py プロジェクト: chfw/youtube2mp3
def save_as_mp3(file_name, clip_info):
    clip = AudioFileClip(file_name)

    t_start, t_end, duration = parse_clip_info(clip_info)
    print(t_start, t_end, duration)
    clip = clip.subclip(t_start=t_start, t_end=t_end)
    if duration:
        clip = clip.set_duration(duration)
    name, suffix = os.path.splitext(file_name)
    try:
        clip.write_audiofile('{}.mp3'.format(name))
    except IndexError:
        print("Please try a bit longer duration")
        raise
コード例 #16
0
def convert_mp3(song_name: str):
    """Función que convierte el formato MP4 a MP3"""

    print("\nConviertiendo la canción a formato 'mp3...")

    try:
        clip = AudioFileClip(song_name)
        clip.write_audiofile(song_name.replace('mp4', 'mp3'))
    except Exception as e:
        print("Hubo un error al convertir la cancación:", e)
        exit(1)

    if song_name.endswith('mp4'):
        remove(song_name)
コード例 #17
0
    def MP4toMP3(self, deletemp4):

        for file in [
                n for n in os.listdir(self.tgt_folder) if re.search('mp4', n)
        ]:
            full_path = os.path.join(self.tgt_folder, file)
            output_path = os.path.join(self.tgt_folder,
                                       os.path.splitext(file)[0] + '.mp3')
            # .subclip(10,)  # disable if do not want any clipping
            clip = AudioFileClip(full_path)
            clip.write_audiofile(output_path)

            if deletemp4:
                print("Deleting {}".format(full_path))
                os.remove(full_path)  # deletes the mp4 file
            else:
                pass
コード例 #18
0
def audio_extraction(video_name):
    """ Receive a video filepath and returns a base64 bytes string of the ogg/vorbis video's audio

    :param video_name: The video file path
    :return: (bytes) base64 bytes string of the video's ogg/vorbis audio.
    """

    audioclip = AudioFileClip(video_name)

    audio_fn = f"{video_name}_audio.ogg"

    audioclip.write_audiofile(audio_fn, codec='vorbis')

    b64audio = base64.b64encode(open(audio_fn, 'rb').read()).decode('utf-8')

    os.remove(audio_fn)

    return b64audio
コード例 #19
0
ファイル: audio_extractor.py プロジェクト: Chepubelja/SubGen
class AudioExtractor():
    """
    Class for extracting audio (.mp3) from video file.
    """
    def __init__(self, filename):
        self.filename = filename

    def load_video(self):
        self.video = VideoFileClip(self.filename)

    def load_mp3(self):
        self.audio = AudioFileClip(self.filename)

    def extract_audio(self):
        self.audio = self.video.audio

    def save_audio(self, audio_path):
        self.audio.write_audiofile(audio_path)
コード例 #20
0
def process_video_exctract_peeks(filepath, do_print):
    filename = path_leaf(filepath)
    print('extracting peeks from ' + filename + '...')

    npy_path = NPY_PATH + filename + NPY_POSTF
    audio_path = AUDIO_FOLDER + filename + AUDIO_POSTF

    audioclip = AudioFileClip(filepath)
    audioclip.write_audiofile(audio_path)

    audio, sr = librosa.load(audio_path)

    print(sr)
    #   FILTER
    x_f = butter_highpass(audio, 30000, sr, order=5)

    o_env = librosa.onset.onset_strength(x_f, sr=sr)
    times = librosa.frames_to_time(np.arange(len(o_env)), sr=sr)
    onset_frames = librosa.util.peak_pick(o_env, 2, 3, 3, 5, 0.3, 4)

    peeks = np.array(librosa.frames_to_time(onset_frames, sr=sr))

    if (do_print):
        print(peeks)

        plt.plot(times, o_env, label='Onset strength')
        plt.vlines(times[onset_frames],
                   0,
                   o_env.max(),
                   color='r',
                   alpha=0.9,
                   linestyle='--',
                   label='Onsets')

        plt.show()

    print("total: " + str(peeks.shape[0]) + " peeks found.")

    print('done.')
    print('----------------------')

    return peeks
コード例 #21
0
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
コード例 #22
0
ファイル: _track.py プロジェクト: the-dotify-project/dotify
    def as_mp3(
        self,
        mp3_path: Path,
        skip_existing: Optional[bool] = False,
        progress_logger: Optional[logging.Logger] = None,
    ) -> Path:
        """Download the track in `.mp3` format.

        Args:
            mp3_path (Path): where should the resulting file be stored
            skip_existing (Optional[bool]): whether or not to overwrite
                an existing file. Defaults to False.
            progress_logger (Optional[logging.Logger]): a logger reporting
                on the download progress. Defaults to None.

        Returns:
            Path: the download location of the `.mp3` file
        """
        # FIXME: genres
        # FIXME: progress bar and logging both for moviepy and pytube

        mp3_path = Path(mp3_path)

        mp4_path = self.as_mp4(mp3_path, skip_existing=skip_existing)

        audio_file_clip = AudioFileClip(str(mp4_path))
        audio_file_clip.write_audiofile(str(mp3_path), logger=progress_logger)

        mp4_path.unlink()

        easy_id3 = EasyID3(mp3_path)

        easy_id3.update(self.id3_tags)

        easy_id3.save(v2_version=3)

        return mp3_path
コード例 #23
0
def get_audio_time(titles):
  time=0
  temp_text=''
  for x in titles:
    time+=0.5
    for y in grouper(x,2,""):
      for m in y:
        temp_text+=m+" "
      time+=get_time_to_read(temp_text)
      time+=0.3
      temp_text=''
  return time+0.2
AUDIO_TIME=get_audio_time(title_texts)
audio=AFC("/gdrive/My Drive/lil daufe/audios/birth_of_a_hero.mp3")
audio=audio.subclip(0,AUDIO_TIME)
audio.write_audiofile("lol.mp3")
class final_video(Scene):
  '''
  complete video
  '''
  CONFIG={
      "include_sound": True,
      "camera_config":{
          "background_color": WHITE,
          "background_opacity":0.4,
      }
  }
  def construct(self):
    self.intro_video()
    self.remove(*self.get_mobjects())
    self.wait()
コード例 #24
0
ファイル: final.py プロジェクト: Sam-Tech-2543/Transcribo
def conversionop(a):
    audioclip = AudioFileClip(a)
    audioclip.write_audiofile("file.wav")
コード例 #25
0
# pip install SpeechRecognition

import speech_recognition as sr
r = sr.Recognizer()

from moviepy.editor import AudioFileClip

my_clip = AudioFileClip("cutwithsound.mp4")
audio = "sound.wav"
my_clip.write_audiofile(audio)

with sr.AudioFile(audio) as source:
    audio = r.record(source)
text= r.recognize_google(audio, language="ru-RU")


filename = "textfile.txt"
f = open(filename, "w+")


remainder = text.split()
while remainder:
    line, remainder = remainder[:5], remainder[5:]
    f.write(' '.join(line) + "\n")


from docx import Document
document = Document()

with open('textfile.txt') as f:
    for line in f:
コード例 #26
0
ファイル: main.py プロジェクト: JN513/youtube_downloader
    def download(self):

        links = self.input.text()
        links = links.split(";")

        if self.path_to_save == None:
            self.path_to_save = self.basedir

        playlist_error = 0
        video_error = 0

        for link in links:
            if self.type == 0:
                try:
                    video = YouTube(link)
                    if self.content == 1:
                        stream = video.streams.get_highest_resolution()
                        self.label_status.setText("Fazendo Download ...")
                        stream.download(self.path_to_save)

                    elif self.content == 0:
                        audio = video.streams.filter(only_audio=True).first()
                        self.label_status.setText("Fazendo Download ...")
                        audio.download(self.path_to_save)
                        self.label_status.setText("Convertendo ...")
                        mp4_path = os.path.join(self.path_to_save,
                                                audio.default_filename)
                        mp3_path = os.path.join(
                            self.path_to_save,
                            os.path.splitext(audio.default_filename)[0] +
                            ".mp3",
                        )
                        new_file = AudioFileClip(mp4_path)
                        new_file.write_audiofile(mp3_path)
                        os.remove(mp4_path)
                except:
                    self.alert(
                        "Erro ao baixar video",
                        "Verifique o link e sua conexão com a internet e tente novamente",
                    )
                    video_error += 1
            if self.type == 1:
                try:
                    playlist = Playlist(link)
                    for url in playlist:
                        try:
                            video = YouTube(url)
                            if self.content == 1:
                                stream = video.streams.get_highest_resolution()
                                self.label_status.setText(
                                    "Fazendo Download ...")
                                stream.download(self.path_to_save)

                            elif self.content == 0:
                                audio = video.streams.filter(
                                    only_audio=True).first()
                                self.label_status.setText(
                                    "Fazendo Download ...")
                                audio.download(self.path_to_save)
                                self.label_status.setText("Convertendo ...")
                                mp4_path = os.path.join(
                                    self.path_to_save, audio.default_filename)
                                mp3_path = os.path.join(
                                    self.path_to_save,
                                    os.path.splitext(audio.default_filename)[0]
                                    + ".mp3",
                                )
                                new_file = AudioFileClip(mp4_path)
                                new_file.write_audiofile(mp3_path)
                                os.remove(mp4_path)
                        except:
                            self.alert(
                                "Erro ao baixar video",
                                "Verifique o link e sua conexão com a internet e tente novamente",
                            )
                            video_error += 1
                except:
                    self.alert(
                        "Erro ao abrir playlist",
                        "Verifique o link e sua conexão com a internet e tente novamente",
                    )
                    playlist_error += 1

        erro = ""
        if playlist_error > 0:
            erro += f" Erro ao abrir {playlist_error} playlists."
        if video_error > 0:
            erro += f" Erro ao baixar {video_error} video(s)."

        self.label_status.setText("Download(s) Concluidos")
        self.alert(
            "Download(s) Concluidos.",
            "Todos os downloads possiveis foram finalizados." + erro,
        )
コード例 #27
0
from moviepy.editor import AudioFileClip
"""
href: https://blog.csdn.net/qq_34769162/article/details/107910036
"""
my_audio_clip = AudioFileClip("../files/bbiamsheep.mp4")
# my_audio_clip.write_audiofile("e:/chrome/my_audio.wav")
my_audio_clip.write_audiofile("../files/bbiamsheep.mp3")
コード例 #28
0
def dowload_videos():
    # Warten, bis alle Videos hinzugefügt wurden
    for thread in threads:
        try:
            thread.join()
        except:
            pass

    # Videos werden nacheinander heruntergeladen
    for video in videos:
        try:
            # wenn nur die Audio gespeichert werden soll,
            if video.file_format == "mp3":

                # Audiostreams
                audio_streams = video.pytube_video.streams.filter(
                    only_audio=True)

                # Audiospur download als mp4
                filepath = audio_streams[0].download(os.getcwd(),
                                                     skip_existing=False)

                # Konvertieren in mp3 und an gewünschtem Speicherort speichern
                audio = AudioFileClip(filepath).subclip(
                    video.start_time, video.end_time)
                audio.write_audiofile(
                    os.path.join(dest_path, video.filename + ".mp3"))

                try:
                    # AurdioReader muss geschlossen werden, um die mp4 Datei zu löschen
                    # manchmal wird ein Fehler erzeugt, mp4 Datei kann trotzdem gelöscht werden
                    # fehler z.B.: https://www.youtube.com/watch?v=YbgDZfK8WR8
                    audio.reader.__del__()
                except Exception as e:
                    pass

                # mp4 Datei wird gelöscht
                os.remove(filepath)

                print(video.pytube_video.title + " gespeichert als " +
                      video.filename + ".mp3")

            # wenn das Video gespeichert werden soll
            elif video.file_format == "mp4":
                # Videostreams
                video_streams = video.pytube_video.streams.filter()

                # mp4 Download an gewünschten speicherort
                filepath = video_streams.get_highest_resolution().download(
                    dest_path,
                    skip_existing=False,
                    filename=video.filename + "(old)")

                # Wenn nicht das ganze Video heruntergeladen werden soll,
                if video.start_time != 0 or video.end_time != video.pytube_video.length:
                    # gewünschter Videoausschnitt wird erstellt
                    videoclip = VideoFileClip(filepath).subclip(
                        video.start_time, video.end_time)

                    # Videoclip wird am gewünschten Speicherort gespeichert
                    videoclip.write_videofile(
                        os.path.join(dest_path, video.filename + ".mp4"))
                    videoclip.reader.close()

                    # ursprüngliches komplettes Video wird gelöscht
                    os.remove(filepath)

                print(video.pytube_video.title + " gespeichert als " +
                      video.filename + ".mp4")
        except Exception as e:
            print("Download von " + video.filename + " fehlgeschlagen\n" +
                  str(e))
コード例 #29
0
    if args.audio:
        # 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.")
コード例 #30
0
ファイル: audio.py プロジェクト: trugle/av2audemo
from moviepy.editor import AudioFileClip
import sys
from you_get import common as you_get  #导入you-get库
import time

directory = r'E:\workspace\python\demo\src'  #设置下载目录
name = str(time.time())  #获取当前时间戳命名
url = 'https://www.bilibili.com/bangumi/play/ss35874'  #需要下载的视频地址
sys.argv = ['you-get', '-o', directory, '-O', name, url]  #sys传递参数执行下载,就像在命令行一样
you_get.main()

video = AudioFileClip('E:\\workspace\\python\demo\\src\\' + name +
                      '.flv')  #读取视频
audio = video.write_audiofile('E:\\workspace\\python\demo\\src\\' + name +
                              '.wav')  #将视频中的音频提取出来