如何从python将wav转换为flac?

Cha*_*s W 8 python audio converter wav flac

我刚开始使用Python并使用PyAudioWave模块从我的麦克风中取出声音并将其转换为.wav文件.

我正在尝试做的是现在将其转换.wav.flac.我已经看到了一些方法,这些方法都涉及安装转换器并将其放置在我的环境路径中并通过它调用它os.system.

有没有其他方法可以转换.wav.flac通过Python?我正在寻找的解决方案需要在Windows和Linux上运行.

Cyb*_*uck 9

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

    from pydub import AudioSegment
    song = AudioSegment.from_wav("test.wav")
    song.export("testme.flac",format = "flac")
Run Code Online (Sandbox Code Playgroud)

许多文件格式支持转换(请参阅此处的ffmpeg支持的文件格式列表https://ffmpeg.org/general.html#Audio-Codecs


Fra*_*urt 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)
Run Code Online (Sandbox Code Playgroud)

安装 Python 音频工具:http : //audiotools.sourceforge.net/install.html

在此处输入图片说明

https://wiki.python.org/moin/Audio/ ( mirror ) 尝试列出所有有用的 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)
Run Code Online (Sandbox Code Playgroud)


val*_*tev 4

也许您正在寻找Python 音频工具。

看来PAT可以为所欲为。