extract audio from mp4 python mp3

Solutions on MaxInterview for extract audio from mp4 python mp3 by the best coders in the world

showing results for - "extract audio from mp4 python mp3"
Hiba
12 Mar 2020
1#!/usr/bin/env python3
2"""
3video_to_mp3.py
4 
5Description:
6Simple script to extract MP3 audio from videos using Python.
7 
8Requirements:
9 - "lame"
10 - "ffmpeg"
11 
12If the libraries are not installed just run the following command in your terminal:
13- On Mac(OS X): brew install lame ffmpeg
14- On Linux(Ubuntu): sudo apt-get install lame ffmpeg
15 
16How to use the script:
17Just run the following command within your terminal replacing "NAME_OF_THE_VIDEO.mp4" by the name of your video file:
18$ python video_to_mp3.py NAME_OF_THE_VIDEO.mp4
19 
20Note.- The video must be within the same directory of the python script, otherwise provide the full path.
21"""
22import sys
23import os
24import time
25 
26 
27def video_to_mp3(file_name):
28    """ Transforms video file into a MP3 file """
29    try:
30        file, extension = os.path.splitext(file_name)
31        # Convert video into .wav file
32        os.system('ffmpeg -i {file}{ext} {file}.wav'.format(file=file, ext=extension))
33        # Convert .wav into final .mp3 file
34        os.system('lame {file}.wav {file}.mp3'.format(file=file))
35        os.remove('{}.wav'.format(file))  # Deletes the .wav file
36        print('"{}" successfully converted into MP3!'.format(file_name))
37    except OSError as err:
38        print(err.reason)
39        exit(1)
40 
41 
42def main():
43    # Confirm the script is called with the required params
44    if len(sys.argv) != 2:
45        print('Usage: python video_to_mp3.py FILE_NAME')
46        exit(1)
47 
48    file_path = sys.argv[1]
49    try:
50        if not os.path.exists(file_path):
51            print('file "{}" not found!'.format(file_path))
52            exit(1)
53 
54    except OSError as err:
55        print(err.reason)
56        exit(1)
57 
58    video_to_mp3(file_path)
59    time.sleep(1)
60 
61 
62if __name__ == '__main__':
63    main()
64