#! /usr/bin/env python
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 檢測添加靜音段時長
# Author: yunhgu
# Date: 2021/11/2 8:53
# Description:
# -------------------------------------------------------------------------------
import logging
import shutil
from pathlib import Path
from time import strftime, localtime, time
from traceback import format_exc
from pydub import AudioSegment
from pydub.silence import detect_silence
from alive_progress import alive_bar
# 日志函數
def log(log_name: str, p_type=""):
journal = logging.getLogger(log_name)
journal.setLevel(level=logging.INFO)
log_file = f"{log_name}{strftime('%Y%m%d%H', localtime(time()))}.log"
format_content = '%(message)s'
if p_type == "time":
format_content = '%(asctime)s - %(levelname)s: %(message)s'
handler = logging.FileHandler(log_file, mode="w", encoding='utf-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter(format_content)
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
console.setFormatter(formatter)
journal.addHandler(handler)
journal.addHandler(console)
return journal
logger = log("檢測添加靜音段時長")
# 檢查路徑是否存在以及是否為空
def check_exist(path):
return Path(path).exists() and path != ""
def add_silence(sound, silence_length, output_file):
one_sec_segment = AudioSegment.silent(duration=2100 - silence_length)
final_song = one_sec_segment + sound
final_song.export(output_file, format="wav")
# 檢測和添加靜音段
def check_and_add(file, qualified_path, unqualified_path):
sound = AudioSegment.from_file(file)
start_end_list = detect_silence(sound, 100, -50, 1)
if len(start_end_list) > 0:
silence_length = start_end_list[0][1] - start_end_list[0][0]
if silence_length < 2000:
output_file = unqualified_path.joinpath(file.name)
add_silence(sound, silence_length, output_file)
logger.info(f"{file}開頭靜音段時長:{silence_length}ms")
else:
shutil.copy(file, qualified_path)
# 主程序
def main(input_path, output_path):
count = len([file for file in input_path.rglob("*.wav")])
with alive_bar(total=count) as bar:
for file in input_path.rglob("*.wav"):
try:
qualified_path = output_path.joinpath("合格音頻")
qualified_path.mkdir(parents=True, exist_ok=True)
unqualified_path = output_path.joinpath("添加靜音音頻")
unqualified_path.mkdir(parents=True, exist_ok=True)
check_and_add(file, qualified_path, unqualified_path)
except Exception as e:
logger.error(f"{file}運行失敗,跳過這個文件。{e}\n{format_exc()}")
finally:
bar()
if __name__ == '__main__':
while True:
print("**** start ****")
input_folder = input("請輸入音頻文件夾:")
output_folder = input("請輸入結果保存文件夾:")
if check_exist(input_folder) and check_exist(output_folder):
try:
main(Path(input_folder), Path(output_folder))
except Exception as ee:
logger.error(f"{format_exc()}:{ee}")
print("**** finished ****")
c = input("請輸入q(不區分大小寫)退出,按其他任意鍵繼續!!!")
if c.lower() == "q":
break
else:
logger.error("輸入的路徑不存在,請檢查后重新輸入!!!")
continue