File size: 1,379 Bytes
e015c08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)}")