python video extract audio code example
Example 1: extract audio from .mp4 python .mp3
"""
video_to_mp3.py
Description:
Simple script to extract MP3 audio from videos using Python.
Requirements:
- "lame"
- "ffmpeg"
If the libraries are not installed just run the following command in your terminal:
- On Mac(OS X): brew install lame ffmpeg
- On Linux(Ubuntu): sudo apt-get install lame ffmpeg
How to use the script:
Just run the following command within your terminal replacing "NAME_OF_THE_VIDEO.mp4" by the name of your video file:
$ python video_to_mp3.py NAME_OF_THE_VIDEO.mp4
Note.- The video must be within the same directory of the python script, otherwise provide the full path.
"""
import sys
import os
import time
def video_to_mp3(file_name):
""" Transforms video file into a MP3 file """
try:
file, extension = os.path.splitext(file_name)
os.system('ffmpeg -i {file}{ext} {file}.wav'.format(file=file, ext=extension))
os.system('lame {file}.wav {file}.mp3'.format(file=file))
os.remove('{}.wav'.format(file))
print('"{}" successfully converted into MP3!'.format(file_name))
except OSError as err:
print(err.reason)
exit(1)
def main():
if len(sys.argv) != 2:
print('Usage: python video_to_mp3.py FILE_NAME')
exit(1)
file_path = sys.argv[1]
try:
if not os.path.exists(file_path):
print('file "{}" not found!'.format(file_path))
exit(1)
except OSError as err:
print(err.reason)
exit(1)
video_to_mp3(file_path)
time.sleep(1)
if __name__ == '__main__':
main()
Example 2: record and store audio in pythn
import pyaudio
import wave
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
fs = 44100
seconds = 3
filename = "output.wav"
p = pyaudio.PyAudio()
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = []
for i in range(0, int(fs / chunk * seconds)):
data = stream.read(chunk)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
print('Finished recording')
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()