python converting video to audio

荒凉一梦 提交于 2020-12-01 10:44:19

问题


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.


回答1:


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.)




回答2:


For those who get the following error while downloading "moviepy.editor" (NeedDownloadError: Need ffmpeg exe. You can download it by calling: imageio.plugins.ffmpeg.download())

Just do this :

import imageio
imageio.plugins.ffmpeg.download()


来源:https://stackoverflow.com/questions/33448759/python-converting-video-to-audio

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