How to extract audio from a video file using python?

拈花ヽ惹草 提交于 2019-11-30 17:00:38

问题


I want to write a python program that could extract audio from a video file (e.g. video.avi). Is there any good library for it? And where should I start from? I tried to use PyMedia, but I couldn't install it on my MacOSX(Mountain Lion).

EDIT: The problem is video.avi is not completely available. Someone is writing on it and adding some frames to it every second. So I wanted to write a code in python to get the video as it comes and extract the audio from it and write it to a file (e.g. audio.mp3, audio.wav). I don't know if ffmpeg can wait for the video to be copied to video.avi.

And I cannot wait for the video to be copied completely and then do the audio extraction. I have to do it as it comes.


回答1:


I don't have a complete solution, but from the ffmpeg docs, it looks like ffmpeg can read an incomplete file by piping to stdin. Example from the docs:

cat test.wav | ffmpeg -i pipe:0

If you must use python, you can always call ffmpeg using subprocess.




回答2:


I had similar problems and coudln't find working exampels with Python codes.

import sys
from moviepy.editor import *

video = VideoFileClip(sys.argv[1])
audio = video.audio
audio.write_audiofile(sys.argv[2])

# 1. Save this file as extract_audio.py
# 2. Type $python extract_audio.py video_for_audio.mp4 audio_from_video.mp3

I wrote a very short blog post for that at medium also.

If you already know the Python, You wouldn't need complicated explanaton.

  1. Select target Video file for audio.
  2. Then, separate only audio file from that video.
  3. Save it as an audio file with given name by sys.argv[2]

What you need to do is just to modify file names after $python extract_audio.py and it will work.



来源:https://stackoverflow.com/questions/19216450/how-to-extract-audio-from-a-video-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!