Manukapp
Manukapp

Reputation: 31

Converting several video files into audio with MoviePy

I have been trying to create a for loop in which Python goes through all of the video files in a folder, and converts each individual video file to a new audio file.
I know that effective code for doing it exists, but only for individual files.

This is my code:

import moviepy
import os
import moviepy.editor 
import tempfile

pathdir = "path/to/dir"

for filename in os.listdir(pathdir):
    filename.endswith(".mkv")
    print(filename)
        
    video = moviepy.editor.VideoFileClip(filename)
    audio = video.audio
    audio.write_audiofile(filename + ".wav")
    
else:
    print("Finished conversion")

And this is what comes up - notice the correct filename is printed, thus identified.

runfile('path/to/dir/convert video to audio script.py', wdir='path/to/dir/')
fg_av_ger_seg0.mkv
Traceback (most recent call last):

OSError: MoviePy error: the file fg_av_ger_seg0.mkv could not be found!
Please check that you entered the correct path.

For your information, here is the code it is based on, which works fine but only for a single file:

import moviepy.editor

video = moviepy.editor.VideoFileClip('sample.mp4')
audio = video.audio
audio.write_audiofile('audio.mp3')

Thank you for your help. I am a beginner, so I apologies in advance if the error is basic! :)

Upvotes: 2

Views: 2379

Answers (1)

Rotem
Rotem

Reputation: 32124

It looks like a path issue...

  • The line filename.endswith(".mkv") supposed to be if filename.endswith(".mkv"):
    You should also concatenate the path with the file name:

     filename = os.path.join(pathdir, filename)  # Prints: path/to/dir/fg_av_ger_seg0.mkv
    
  • Instead of listing all the files, and look for files that ends with .mkv, you may filter the list from advance using glob.glob:

     mkv_filenames_list = glob.glob(os.path.join(pathdir, "*.mkv"))
    
  • It's recommended to replace the .mkv extension with .wav extension (not just adding .wav):

     wav_file_name = filename.replace('.mkv', '.wav')
    
  • Make sure that the MKV files are in the correct path, and that you have read permissions to the files, and write permissions to the folder.


Here is a complete code sample (change pathdir, or put the Python script at the same folder as the MKV files):

import moviepy
import os
import glob
import moviepy.editor 

pathdir = "."

# Get a list of all the files with .mkv extension in pathdir folder.
mkv_filenames_list = glob.glob(os.path.join(pathdir, "*.mkv"))

for filename in mkv_filenames_list:
    print(filename)
        
    video = moviepy.editor.VideoFileClip(filename)
    audio = video.audio

    # Some of my MKV files are without audio.
    if audio is not None:
        wav_file_name = filename.replace('.mkv', '.wav')  # Replace .mkv with .wav
        audio.write_audiofile(wav_file_name)
else:
    print("Finished conversion")

Upvotes: 3

Related Questions