Unity uses Python for volume consistency processing of special effects

Unity uses Python for volume consistency processing of special effects

foreword

Various sound effects found on the Internet sound high and low in the game, and a Pythonscript can make the messy sound sound consistent.

sound processing

source code

tip:
target_db=-20Indicates the target decibel level is -20 dB. In audio processing, decibels (dB) are the unit used to measure volume. A higher decibel level means louder volume, while a lower decibel level means quieter volume.
In this script, we use a target decibel level to unify the volume of an audio file. If the current decibel level of an audio file is lower than the target decibel level, the script will increase the volume of the audio to the target level. Conversely, if the current decibel level of an audio file is higher than the target decibel level, the script will reduce the volume of the audio to bring it closer to the target level.
In this case, the target decibel level -20 dBis a common choice, as it is generally considered an appropriate volume level for audio that provides clear sound without being overly loud.
You can adjust the parameters according to your own needs target_dband choose the target volume level suitable for your application scenario.

import os
from pydub import AudioSegment
from pydub.utils import make_chunks

def normalize_audio_volume(input_folder, output_folder, target_db=-20):
    # 创建输出目录
    os.makedirs(output_folder, exist_ok=True)
    
    # 获取输入文件夹中的所有文件
    file_list = os.listdir(input_folder)
    
    # 遍历文件夹中的每个文件
    for file_name in file_list:
        input_path = os.path.join(input_folder, file_name)
        
        # 检查文件是否是音频文件
        if file_name.endswith('.mp3') or file_name.endswith('.wav'):
            print("处理文件:", file_name)
            
            # 使用pydub库加载音频文件
            audio = AudioSegment.from_file(input_path)
            
            # 计算音频文件的当前分贝级别
            current_db = audio.dBFS
            
            # 计算音频文件需要增加或减少的分贝数
            db_diff = target_db - current_db
            
            # 调整音频文件的音量
            normalized_audio = audio + db_diff
            
            # 构建输出文件路径
            output_path = os.path.join(output_folder, file_name)
            
            # 将调整后的音频文件保存到输出文件夹
            normalized_audio.export(output_path, format=file_name[-3:])
            print("已调整音量")
    
    print("音量调整完成!输出文件位于:", output_folder)

# 测试代码
input_folder = "D:\Project\Python\\normalize_audio\\audio"  # 将此处的路径替换为实际文件夹的路径
output_folder = "D:\Project\Python\\normalize_audio\\output"  # 将此处的路径替换为实际的输出文件夹路径
normalize_audio_volume(input_folder, output_folder)

thank you

ChatGPT

Guess you like

Origin blog.csdn.net/a71468293a/article/details/130947459