Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 548
programmer44 Avatar asked Oct 31 '15 06:10

programmer44


People also ask

How do I extract audio from a video file?

One of the quickest ways to extract the audio from a video file on a Windows PC is to use the VLC Media Player. Although VLC is a free media player app, it has some secret features, including conversion options built into it as well. You can use those conversion options to convert your video file into an audio file.

How do I get audio in Python?

The python-sounddevice and pyaudio libraries provide ways to record audio with Python. python-sounddevice records to NumPy arrays and pyaudio records to bytes objects. Both of these can be stored as WAV files using the scipy and wave libraries, respectively.


2 Answers

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

like image 115
Zulko Avatar answered Oct 15 '22 21:10

Zulko


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()
like image 40
Ayoub Marouan Avatar answered Oct 15 '22 21:10

Ayoub Marouan