簡體   English   中英

如何從python將wav轉換為flac?

[英]How to convert wav to flac from python?

我剛開始使用Python並使用PyAudioWave模塊從麥克風中獲取聲音並將其轉換為.wav文件。

我現在要做的是將.wav轉換為.flac 我已經看到了一些方法,這些方法都涉及安裝轉換器並將其放在我的環境路徑中並通過os.system調用它。

有沒有其他方法可以通過Python將.wav轉換為.flac 我正在尋找的解決方案需要在Windows和Linux上運行。

我沒有測試過這個解決方案,但你可以使用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

可能你正在尋找Python音頻工具。

似乎PAT可以做任何你想做的事情。

下面是使用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音頻工具: 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM