目录

时间:2017-06-05 11:11:57

标签: python

我想将每个进入输入目录的新wav文件转换为mp3上的另一个目录。我一直在寻找如何转换这些文件,但是,我不知道如何在输入目录上添加一个监听器,或者它是否可能?

编辑: 对不起,我忘了与您分享我已有的代码。我使用ffmpeg转换音频文件

import os, sys, glob

FFMPEG_PATH = "C:\\ffmpeg\\bin"

fileName = ""
fileExt = ""

wavdir = ""
mp3dir = ""


for file in glob.glob('wav/*.wav'):

    # get the name  without .ext
    fileName = os.path.basename(file)
    fileName = fileName.split(".")[0]

    # verify if no mp3 file with thesame name exist
    if not os.path.isfile('./mp3/'+fileName+".mp3"):

        # set var with the 2 types files dir
        wavdir = file
        mp3dir = "mp3/"+fileName+".mp3"

        # start the convertion with ffmpeg by commande line
        os.system("ffmpeg -i "+wavdir+" "+mp3dir)

3 个答案:

答案 0 :(得分:1)

这非常不理想,但应该完成工作

import os, time

SLEEPTIME = 0.5
TARGET_DIRECTORY = 'path_of_your_folder'

while True:
    time.sleep(SLEEPTIME)
    files = os.listdir(TARGET_DIRECTORY)
    for file in files:
        if file.endswith('.wav'):
            CONVERT

答案 1 :(得分:1)

制作while True循环。然后在循环中,您使用for item in os.listdir(yourdir)创建另一个循环,然后移动每个项目,然后您可以使time.sleep(1)减少延迟。

答案 2 :(得分:1)

我不确定这是不是最好的主意,但是您可以分配一个进程或一个线程来检查文件是否每隔X秒被添加到目录中:

import os
import time
wav_files_path = "/WAV_dir_path"
prev_files = os.listdir(wav_files_path)
x = 1 # time to sleep
while True:
    files = os.listdir(wav_files_path)
    if len(files) > len(prev_files):  # if files are not deleted it's better to check if any files were added
        # NEW FILE(S) ADDED
        for f in files:
            if f not in prev_files:
                convert_file(f)
    prev_files = files
    time.sleep(x)