import os | |
import ffmpeg | |
DEBUG=True | |
def get_audio_from_video(video_path: str, output_folder: str) -> str: | |
""" | |
Extract audio from video and save it as mp3. | |
Args: | |
video_path (str): Path to the video file | |
output_folder (str): Path to folder where audio will be saved | |
Returns: | |
str: Path to the saved audio file | |
Raises: | |
Exception: If video file doesn't exist | |
Exception: If there's an error extracting the audio | |
""" | |
# Validate video exists | |
if not os.path.exists(video_path): | |
raise Exception(f"Video file not found: {video_path}") | |
# Create output folder if it doesn't exist | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
try: | |
# Generate output path | |
audio_filename = "download_audio.mp3" | |
audio_path = os.path.join(output_folder, audio_filename) | |
if DEBUG: | |
if os.path.exists(audio_path): | |
return audio_path | |
# Extract audio using ffmpeg | |
stream = ffmpeg.input(video_path) | |
stream = ffmpeg.output(stream, audio_path, acodec='libmp3lame') | |
ffmpeg.run(stream, overwrite_output=True) | |
return audio_path | |
except Exception as e: | |
raise Exception(f"Error extracting audio from video: {str(e)}") |