ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-11-02 10:00:13  阅读:253  来源: 互联网

标签:input python import 音频 file output path 静音 silence


#! /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

标签:input,python,import,音频,file,output,path,静音,silence
来源: https://www.cnblogs.com/yunhgu/p/15497469.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有