当前位置: 首页 > news >正文

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.")
http://www.dtcms.com/a/602162.html

相关文章:

  • 用什么软件写网站荷城网站设计
  • 长治哪家公司做网站好怎么做网站教程视频
  • 跟踪导论(三)——滤波的释义位置信息的“观测+修正”
  • 一个电商网站开发周期是多久搜索引擎营销流程是什么?
  • 计算机做网站难吗网站建设费可以走办公费吗
  • 做公众号还是网站建网站哪家划算
  • 从App时代到智能体时代,如何打破“三堵墙”
  • jsp怎么拿到url参数
  • 有机蔬菜:清爽解腻的炖锅搭档
  • 网站的时间对齐应该怎么做wordpress中文评论插件
  • 515ppt网站建设岳麓区专业的建设网站公司
  • mysql第5次作业---hyx
  • LLM的“哥白尼革命”:物理AI与世界模型,AI的下一个战场!
  • VC软件编译C语言 | 详细教程与常见问题解答
  • 高职单招与统招比较及职业发展指南
  • Cursor vs Claude Code:AI编程工具深度对比与选择指南
  • php论坛网站源码下载大型购物网站设计
  • 网站建设标书样本如何修改wordpress登录域名
  • 深圳网站建设联系方式crm客户管理系统论文
  • Python 100例:深入学习与实践指南
  • “系统性”学习高并发路线
  • VL25 输入序列连续的序列检测
  • 如何做条形码网站怎么搞浏览器如何推广自己网站
  • 系统之美—人文行走
  • 用Python和Websockets库构建一个高性能、低延迟的实时消息推送服务
  • 海尔网站建设水平河北廊坊seo网站建设网站优化
  • 小型深圳网站定制开发最专业的网站建设
  • 中山网站优化排名徐州祥云做网站
  • 8、hall速度控制——速度电流双闭环控制(一)
  • 网页版C语言编译器 | 在线体验C语言编程,快速编译与调试