Python压缩音乐文件大小
1.保证下载了ffmpeg
2.下载了python
3.保存运行就完了例:compress_music.py
4.效果评价是有用,但不多
import os
import subprocess
import shutil
from pathlib import Path# ------------------ 配置路径 ------------------
input_folder = "C:/Users/Desktop/temp/music/" # 修改为你的源音乐文件夹
output_folder = "C:/Users/Desktop/temp/small" # 修改为输出文件夹# 支持的音频格式
audio_extensions = {'.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a', '.wma', '.ac3'}# 创建输出文件夹(如果不存在)
os.makedirs(output_folder, exist_ok=True)def convert_file(input_path, output_path):"""使用 ffmpeg 转换音频文件"""ext = input_path.suffix.lower()original_size = input_path.stat().st_size # 获取原文件大小if ext == '.wav':# WAV -> FLAC 无损压缩output_file = output_path.with_suffix('.flac')cmd = ['ffmpeg', '-y', '-i', str(input_path),'-c:a', 'flac', '-compression_level', '8',str(output_file)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)elif ext == '.flac':# FLAC 已是无损压缩,可直接复制或重新压缩(可选)output_file = output_path.with_suffix('.flac')cmd = ['ffmpeg', '-y', '-i', str(input_path),'-c:a', 'flac', '-compression_level', '8',str(output_file)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)elif ext == '.mp3':# MP3 是有损格式,我们不做重编码,直接复制(避免音质下降)output_file = output_path.with_suffix('.mp3')shutil.copy(input_path, output_file)return output_fileelse:# 其他格式转为 AAC 或保留原格式(可根据需要调整)# 这里以转成 AAC 为例(有损,但体积小)output_file = output_path.with_suffix('.m4a')cmd = ['ffmpeg', '-y', '-i', str(input_path),'-c:a', 'aac', '-b:a', '192k',str(output_file)]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)# 比较文件大小,如果新文件更大则使用原文件if output_file.exists():new_size = output_file.stat().st_sizeif new_size > original_size:print(f" Warning: New file ({new_size} bytes) is larger than original ({original_size} bytes)")output_file.unlink() # 删除较大的新文件shutil.copy(input_path, output_file) # 使用原文件print(f" Used original file instead")return output_filedef process_audio_files():input_path = Path(input_folder)output_path_root = Path(output_folder)# 验证输入和输出路径不相同if input_path.resolve() == output_path_root.resolve():print("Error: Input and output folders cannot be the same")return# 只处理当前目录的文件,不递归子目录for file_path in input_path.glob('*'):if file_path.is_file() and file_path.suffix.lower() in audio_extensions:# 构造输出路径,保持目录结构rel_path = file_path.relative_to(input_path)output_file_stem = output_path_root / rel_path.with_suffix('') # 去掉后缀用于拼接# 直接处理文件,不管是否存在同名文件target_output = Noneif file_path.suffix.lower() in ['.wav', '.flac']:print(f"Processing: {file_path} -> {output_file_stem.with_suffix('.flac')}")target_output = convert_file(file_path, output_file_stem)elif file_path.suffix.lower() == '.mp3':output_mp3 = output_file_stem.with_suffix('.mp3')print(f"Copying: {file_path} -> {output_mp3}")shutil.copy(file_path, output_mp3)target_output = output_mp3else:output_m4a = output_file_stem.with_suffix('.m4a')print(f"Converting: {file_path} -> {output_m4a}")target_output = convert_file(file_path, output_file_stem)if target_output:print(f"Saved: {target_output}")if __name__ == "__main__":if not os.path.exists(input_folder):print(f"Error: Input folder does not exist: {input_folder}")else:process_audio_files()print("✅ All audio files processed.")