How to convert wav to flac from python?

18,644

Solution 1

May be you're looking for Python Audio Tools.

It seems PAT can do whatever you want.

Solution 2

I have not tested this solution but you can use pydub

    from pydub import AudioSegment
    song = AudioSegment.from_wav("test.wav")
    song.export("testme.flac",format = "flac")

the conversion is supported with numerous file formats (see the ffmpeg supported file formats list herehttps://ffmpeg.org/general.html#Audio-Codecs

Solution 3

Here is a code example using the Python library Python Audio Tools to convert a .wav file to a .flac file:

import audiotools
filepath_wav = 'music.wav'
filepath_flac = filepath_wav.replace(".wav", ".flac")
audiotools.open(filepath_wav).convert(filepath_flac,
                                      audiotools.FlacAudio, compression_quality)

To install Python Audio Tools: http://audiotools.sourceforge.net/install.html

enter image description here

https://wiki.python.org/moin/Audio/ (mirror) attempts to list all useful Python libraries to work with audio in combination with Python.


A longer Python script to multithreadedly batch convert wav files to FLAC files, from http://magento4newbies.blogspot.com/2014/11/converting-wav-files-to-flac-with.html

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
From http://magento4newbies.blogspot.com/2014/11/converting-wav-files-to-flac-with.html
"""
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)
Share:
18,644
Charles W
Author by

Charles W

Updated on June 14, 2022

Comments

  • Charles W
    Charles W about 2 years

    I've just started using Python and am using the PyAudio and Wave modules to take sound from my microphone and convert it to a .wav file.

    What I'm trying to do is now convert that .wav to a .flac. I've seen a few ways to do this which all involve installing a converter and placing it in my environmental PATH and calling it via os.system.

    Are there any other ways to convert a .wav to a .flac via Python? The solution I'm looking for needs to work on both Windows and Linux.

  • Charles W
    Charles W about 10 years
    Do you know how Python Audio Tools compares in speed to say subprocess.popen(flac_converter)?
  • valignatev
    valignatev about 10 years
    I know PAT can use multiple cpu cores for conversion. It's pretty fast. And subprocess.popen(converter)'s speed very depends on speed of 3rd party audio software.
  • GodSaveTheDucks
    GodSaveTheDucks over 8 years
    to get pydub use pip : (sudo) pip install pydub
  • Joe.Zeppy
    Joe.Zeppy over 7 years
    does this put the audio file completely into memory? If so is there a way to do it in a more streaming approach
  • Stryker
    Stryker over 6 years
    Can I just pass the wav file to this python script? i.e python pythonsciptwavtoflacConverter.py myfile.wav (assume naming the script above: pythonscriptwavtoflacConverter.