python检测音频静音段并添加静音段

#! /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("请输入结果保存文件夹:")
        # input_folder = r"F:\任务\2021\许倩\检测添加静音段时长\data"
        # output_folder = r"F:\任务\2021\许倩\检测添加静音段时长\result"
        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
上一篇:javascript – ES6 – 如何声明隐式类成员?


下一篇:专 注 于 阅 读 的 博 客 园 主 题 silence