import os import math import shutil import tempfile import datetime import subprocess from enum import IntEnum from typing import Self from gtts import gTTS class LinkType(IntEnum): SOFT = 1 HARD = 2 class Audio: def __init__(self): self._audio_dir = None self._audio_filename = None @classmethod def from_file(cls, audio_filepath: str) -> Self: audio_filepath = os.path.abspath(audio_filepath) if not os.path.isfile(audio_filepath): raise FileNotFoundError(f'No audio file {audio_filepath}') audio = cls() audio._audio_dir = tempfile.TemporaryDirectory() audio._audio_filename = os.path.basename(audio_filepath) cls._copy_file(audio_filepath, audio._get_filepath(), link_type=None) return audio @classmethod def from_tts(cls, text: str) -> Self: audio = cls() audio._audio_dir = tempfile.TemporaryDirectory() audio._audio_filename = 'tts.mp3' tts_audio = gTTS(text=text, lang='en') tts_audio.save(audio._get_filepath()) return audio @staticmethod def _copy_file(src_filepath: str, dest_filepath: str, link_type: LinkType | None = None) -> None: match link_type: case LinkType.SOFT: # Symbolic link to file os.symlink(src_filepath, dest_filepath) case LinkType.HARD: # Hard link to file os.link(src_filepath, dest_filepath) case _: # Copy file shutil.copyfile(src_filepath, dest_filepath) @staticmethod def _move_file(src_filepath: str, dest_filepath: str, link_type: LinkType | None = None) -> None: match link_type: case LinkType.HARD: # Hard link to file os.link(src_filepath, dest_filepath) os.remove(src_filepath) case _: # Move file shutil.move(src_filepath, dest_filepath) def _get_filepath(self) -> str: return os.path.join(self._audio_dir.name, self._audio_filename) def save(self, save_path: str) -> None: if self._audio_dir is None or self._audio_filename is None: raise ValueError('Cannot save empty Audio object') self._copy_file(self._get_filepath(), save_path, link_type=None) def get_duration(self) -> float: ffprobe_process = subprocess.run([ 'ffprobe', '-i', self._get_filepath(), '-show_entries', 'format=duration', '-v', 'quiet', '-of','csv=p=0' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) ffprobe_process.check_returncode() return float(ffprobe_process.stdout.strip()) def loop(self, count: int = 1, duration: float = None) -> Self: output_filename = '.ffmpeg'.join(os.path.splitext(self._audio_filename)) ffmpeg_args = ['ffmpeg'] if duration is None: ffmpeg_args.extend([ '-stream_loop', str(count - 1), '-i', self._get_filepath(), '-c', 'copy' ]) else: ffmpeg_args.extend([ '-stream_loop', str(math.ceil(duration / self.get_duration()) - 1), '-i', self._get_filepath(), '-c', 'copy', '-t', str(duration) ]) ffmpeg_args.append(os.path.join(self._audio_dir.name, output_filename)) ffmpeg_process = subprocess.run(ffmpeg_args, stderr=subprocess.DEVNULL, text=True) ffmpeg_process.check_returncode() # Move output file back to original location os.remove(self._get_filepath()) self._move_file(os.path.join(self._audio_dir.name, output_filename), self._get_filepath(), link_type=LinkType.HARD) return self def concat(self, *args: Self) -> Self: concat_filepath = os.path.join(self._audio_dir.name, 'concat.txt') with open(concat_filepath, 'w') as concat_file: concat_file.writelines([f'file \'{audio._get_filepath()}\'\n' for audio in (self,) + args]) output_filename = '.ffmpeg'.join(os.path.splitext(self._audio_filename)) ffmpeg_process = subprocess.run([ 'ffmpeg', '-f', 'concat', '-safe', '0', '-i', concat_filepath, '-c', 'copy', os.path.join(self._audio_dir.name, output_filename) ], stderr=subprocess.DEVNULL, text=True) os.remove(concat_filepath) ffmpeg_process.check_returncode() # Move outupt file back to original location os.remove(self._get_filepath()) self._move_file(os.path.join(self._audio_dir.name, output_filename), self._get_filepath(), link_type=LinkType.HARD) return self def trim(self, start: datetime.time = datetime.time(0, 0, 0, 0), end: datetime.time = None) -> Self: output_filename = '.ffmpeg'.join(os.path.splitext(self._audio_filename)) ffmpeg_args = [ 'ffmpeg', '-i', self._get_filepath(), '-c', 'copy', '-ss', start.strftime('%H:%M:%S.%f') ] if end is not None: ffmpeg_args.extend([ '-to', end.strftime('%H:%M:%S.%f'), ]) ffmpeg_args.append(os.path.join(self._audio_dir.name, output_filename)) ffmpeg_process = subprocess.run(ffmpeg_args, stderr=subprocess.DEVNULL, text=True) ffmpeg_process.check_returncode() # Move outupt file back to original location os.remove(self._get_filepath()) self._move_file(os.path.join(self._audio_dir.name, output_filename), self._get_filepath(), link_type=LinkType.HARD) return self