python检测音频静音段并添加静音段
2021/11/2 11:11:45
本文主要是介绍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
这篇关于python检测音频静音段并添加静音段的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Python基础编程
- 2024-11-25Python编程基础:变量与类型
- 2024-11-25Python编程基础与实践
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南