Pages

Friday, November 21, 2014

Converting wav files to flac with python and audiotools

This is not about Magento programming ;-)

I was looking for a (free) tools to convert all my wav files to flac. As such, not a special task, there are many tools around. But all the GUI tools I found, had big issues to run in batch mode with thousands of files to convert. 

Eventually I found track2track from audiotools. The only problem was here, I couldn't get it working in batch mode with setting the right params for the output (converted) file names. So I decided to wrap my own script around audiotools. 

Certainly not really performant, but it does the job.
Here my first try:


from Queue import Queue
import logging
import os
from threading import Thread
import audiotools
from audiotools.wav import InvalidWave

"""
Wave 2 Flac converter script
using audiotools
"""
class W2F:

    logger = ''

    def __init__(self):
        global logger
        # create logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # create a file handler
        handler = logging.FileHandler('converter.log')
        handler.setLevel(logging.INFO)

        # create a logging format
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)

        # add the handlers to the logger
        logger.addHandler(handler)

    def convert(self):
        global logger
        file_queue = Queue()
        num_converter_threads = 5

        # collect files to be converted
        for root, dirs, files in os.walk("/Volumes/music"):

            for file in files:
                if file.endswith(".wav"):
                    file_wav = os.path.join(root, file)
                    file_flac = file_wav.replace(".wav", ".flac")

                    if (os.path.exists(file_flac)):
                        logger.debug(''.join(["File ",file_flac, " already exists."]))
                    else:
                        file_queue.put(file_wav)

        logger.info("Start converting:  %s files", str(file_queue.qsize()))

        # Set up some threads to convert files
        for i in range(num_converter_threads):
            worker = Thread(target=self.process, args=(file_queue,))
            worker.setDaemon(True)
            worker.start()

        file_queue.join()

    def process(self, q):
        """This is the worker thread function.
        It processes files in the queue one after
        another.  These daemon threads go into an
        infinite loop, and only exit when
        the main thread ends.
        """
        while True:
            global logger
            compression_quality = '0' #min compression
            file_wav = q.get()
            file_flac = file_wav.replace(".wav", ".flac")

            try:
                audiotools.open(file_wav).convert(file_flac,audiotools.FlacAudio, compression_quality)
                logger.info(''.join(["Converted ", file_wav, " to: ", file_flac]))
                q.task_done()
            except InvalidWave:
                logger.error(''.join(["Failed to open file ", file_wav, " to: ", file_flac," failed."]), exc_info=True)
            except Exception, e:
                logger.error('ExFailed to open file', exc_info=True)




As you can see, there is a bit of multithreading implemented. Looks like it works a bit faster than my first try. Anyway, it's only a dummy example, improve it as you like!

1 comment:

  1. I highly recommend iDealshare VideoGo which has both Mac and Windows version.

    It can convert WAV files to FLAC with almost no loss of audio Quality.

    Step by step guide at http://www.idealshare.net/audio-converter/wav-to-flac-converter.html

    It also can convert WAV to Apple Lossless ALAC, M4A, OGG, MP3, AIFF, WMA, DTS, etc.

    ReplyDelete