如何用Python将wav转换为flac?

13 投票
3 回答
23184 浏览
提问于 2025-04-18 07:54

我刚开始学习Python,正在使用PyAudioWave这两个模块,从我的麦克风录音并把它保存成.wav文件。

现在我想把这个.wav文件转换成.flac格式。我看到有几种方法可以做到这一点,都是需要安装一个转换工具,然后把它放到我的环境变量PATH里,通过os.system来调用。

有没有其他方法可以通过Python把.wav转换成.flac呢?我希望这个解决方案在Windows和Linux上都能用。

3 个回答

5

这里有一个使用Python库Python Audio Tools的代码示例,展示如何把一个.wav文件转换成.flac文件:

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

要安装Python Audio Tools,可以访问这个链接:http://audiotools.sourceforge.net/install.html

这里插入图片描述

https://wiki.python.org/moin/Audio/镜像链接)尝试列出所有与音频相关的有用Python库,方便和Python一起使用。


下面是一个较长的Python脚本,能够多线程批量将wav文件转换为FLAC文件,来源于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)
19

我还没有测试这个解决方案,但你可以使用pydub

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

这个转换支持很多种文件格式(可以在这里查看ffmpeg支持的文件格式列表https://ffmpeg.org/general.html#Audio-Codecs)。

4

也许你在找的是Python音频工具

看起来这个工具可以满足你所有的需求。

撰写回答