Python extract audio from video

Introduction

The video written in OpenCV using the VideoCapture class has no audio. If you want to further process the audio, you need to use a library- MoviePy . This library is a Python video editing library that can be cropped, spliced, title inserted, video synthesis, video processing and Custom effects.

installation

pip install moviepy

Code

from moviepy.editor import *

video = VideoFileClip('平妖往事live.mp4')
audio = video.audio
audio.write_audiofile('test.mp3')
MoviePy - Writing audio in test.mp3
MoviePy - Done.

You can use the ffmpeg-python library directly without installing the moviepy video editing library, see reference 4, the code is slightly more complicated

audio format

extensions_dict = {
    
     "mp4":  {
    
    'type':'video', 'codec':['libx264','libmpeg4', 'aac']},
                    'ogv':  {
    
    'type':'video', 'codec':['libtheora']},
                    'webm': {
    
    'type':'video', 'codec':['libvpx']},
                    'avi':  {
    
    'type':'video'},
                    'mov':  {
    
    'type':'video'},

                    'ogg':  {
    
    'type':'audio', 'codec':['libvorbis']},
                    'mp3':  {
    
    'type':'audio', 'codec':['libmp3lame']},
                    'wav':  {
    
    'type':'audio', 'codec':['pcm_s16le', 'pcm_s24le', 'pcm_s32le']},
                    'm4a':  {
    
    'type':'audio', 'codec':['libfdk_aac']}
                  }

It can be seen that the four formats of ogg, mp3, wav and m4a are supported. Personal test of m4a output fails. It is recommended to use only mp3 and wav

The test 2-minute video export mp3 is 1.83Mb, wav is 20.1Mb

mp3 is a lossy format, wav is a lossless format, choose as needed

Remarks

To achieve a lower level of audio and video processing applications ffmpeg

references

  1. How to extract Audio from the Video with Python
  2. MoviePy tutorial
  3. moviepy · PyPI
  4. Extract Audio From Video Using Python and FFmpeg
  5. MoviePy-Chinese document

Guess you like

Origin blog.csdn.net/qq_33254766/article/details/108766915