Python从视频中提取音频

OpenCV中使用VideoCapture类写的视频是没有音频的,如果要进一步处理音频则需要用到一个库——MoviePy,这个库是Python视频编辑库,可裁剪、拼接、标题插入、视频合成、视频处理和自定义效果

代码

from moviepy.editor import *

video = VideoFileClip('test.mp4')
audio = video.audio
audio.write_audiofile('test.mp3')

不安装moviepy视频编辑库可以直接使用ffmpeg-python库,见参考文献4,代码稍微复杂点

音频格式

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']}
                  }

可看到支持ogg、mp3、wav和m4a四种格式,个人测试m4a输出失败,建议只用mp3和wav

测试2分钟的视频导出mp3为1.83Mb,wav为20.1Mb

mp3是有损格式,wav是无损格式,按需选择

备注

要实现更底层的音视频处理应用ffmpeg

参考文献

  1. How to extract Audio from the Video with Python – Steadylearner – Medium https://medium.com/@steadylearner/how-to-extract-audio-from-the-video-with-python-aea325f434b6
  2. MoviePy - 中文文档(一个专业的python视频编辑库)教程 - ucsheep-You see sheep! - CSDN博客 https://blog.csdn.net/ucsheep/article/details/80999939
  3. moviepy · PyPI https://pypi.org/project/moviepy/
  4. Extract Audio From Video Using Python and FFmpeg · Infinite.ft的博客 https://www.infiniteft.xyz/2018/02/20/extract-audio-from-video-using-python-and-ffmpeg/

你可能感兴趣的:(Python从视频中提取音频)