pythonbashaudiovideoffmpeg

python converting video to audio


We are working on a project to convert video to audio, and this is the sample code:

from converter import Converter
from moviepy.editor import *
c = Converter()
clipv = 'g.mp4'
clipc = VideoFileClip(clipv).subclip(0,20)
conv = c.convert(clipc, 'clip5.mp3', {'format':'mp3','audio':{'codec': 'mp3','bitrate':'22050','channels':1}})
for timecode in conv:
    pass    

However, it gives me this error

Traceback (most recent call last)
 File "del.py", line 7, in <module>
    for timecode in conv:
 File "/usr/local/lib/python2.7/dist-packages/converter/__init__.py", line 181, in convert
    if not os.path.exists(infile):
 File "/usr/lib/python2.7/genericpath.py", line 18, in exists
    os.stat(path)
TypeError: coercing to Unicode: need string or buffer, instance found

Of course, the other alternative is to use ffmpeg, but the problem is that the video in this case is an object instance, and as of now I am yet to find a way of passing object instances from python to bash.

The video object could be written as a video file, but that will lead to lots of time wastage, as the conversion takes place inside a loop.

It is quite time consuming to have to write the video file time and again, so as to easily extract audio from it.

I would highly appreciate any solution that will either help me get around the above error, or any that will allow me to pass the video fileclip object instance to bash ffmpeg as a variable.


Solution

  • Try this:

    import moviepy.editor as mp
    clip = mp.VideoFileClip("myvideo.mp4").subclip(0,20)
    clip.audio.write_audiofile("theaudio.mp3")
    

    You can add a lot of parameters in write_audiofile (format, codec, bitrate, fps, etc.)