# -*- coding: utf-8 -*- """ Convert all MP3 files to OGG in all folders and subfolders starting at the location of this source file. @author: Michael Currie """ import os, collections from glob import glob # For mp3 to ogg conversion # https://github.com/jiaaro/pydub from pydub import AudioSegment def flatten(list_of_lists): """ Recursively travel through a list of lists, flattening them. """ # From http://stackoverflow.com/questions/2158395 for element in list_of_lists: # If it's iterable but not a string or bytes, then recurse, otherwise # we are at a "leaf" node of our traversal if(isinstance(element, collections.Iterable) and not isinstance(element, (str, bytes))): for sub_element in flatten(element): yield sub_element else: yield element cur_dir = os.path.dirname(__file__) # Create a generator giving all the mp3s # (From http://stackoverflow.com/questions/18394147/) mp3_paths = (glob(os.path.join(x[0], '*.mp3')) for x in os.walk(cur_dir)) # Flatten it, since the lists might contain other lists #mp3_paths_flat = flatten(mp3_paths) mp3_paths_flat = list(flatten(mp3_paths)) # Convert each mp3 to ogg in place, then delete the mp3 for mp3_path in mp3_paths_flat: print("Converting %s " % mp3_path) # Prepare the new name for the converted song song_folder, song_filename = os.path.split(mp3_path) new_song_filename = os.path.splitext(song_filename)[0] + '.ogg' ogg_path = os.path.join(song_folder, new_song_filename) # Perform the actual import / export song = AudioSegment.from_mp3(mp3_path) song.export(ogg_path, format='ogg', codec='libvorbis') # Delete the original file os.remove(mp3_path) print("Done converting all %d files." % len(mp3_paths_flat))