当前位置: 代码网 > it编程>前端脚本>Python > python如何将aac转为mp3,保持原有目录结构

python如何将aac转为mp3,保持原有目录结构

2024年11月08日 Python 我要评论
将aac转为mp3,保持原有目录结构需要提前安装ffmpegimport osimport subprocessimport timefrom concurrent.futures import th

将aac转为mp3,保持原有目录结构

需要提前安装ffmpeg

import os
import subprocess
import time
from concurrent.futures import threadpoolexecutor, as_completed

def convert_file(input_path, output_path):
    command = [
        'ffmpeg',
        '-y',  # 自动覆盖现有文件
        '-i', input_path,
        '-acodec', 'libmp3lame',
        '-b:a', '192k',
        output_path
    ]
    try:
        subprocess.run(command, check=true, stderr=subprocess.pipe, timeout=300)  # 5分钟超时
        return f"converted: {output_path}"
    except subprocess.calledprocesserror as e:
        return f"error converting {input_path}: {e.stderr.decode()}"
    except subprocess.timeoutexpired:
        return f"timeout converting {input_path}"

def convert_aac_to_mp3(input_dir, output_dir):
    start_time = time.time()
    total_files = 0
    processed_files = 0
    converted_files = 0

    with threadpoolexecutor(max_workers=os.cpu_count()) as executor:
        futures = []

        for root, _, files in os.walk(input_dir):
            for filename in files:
                if filename.lower().endswith('.aac'):
                    total_files += 1
                    input_path = os.path.join(root, filename)
                    rel_path = os.path.relpath(root, input_dir)
                    output_filename = os.path.splitext(filename)[0] + '.mp3'
                    output_path = os.path.join(output_dir, rel_path, output_filename)
                    
                    os.makedirs(os.path.dirname(output_path), exist_ok=true)
                    
                    futures.append(executor.submit(convert_file, input_path, output_path))

        for future in as_completed(futures):
            result = future.result()
            print(result)
            processed_files += 1
            if "converted" in result:
                converted_files += 1
            print(f"progress: {processed_files}/{total_files} files processed")

    end_time = time.time()
    print(f"\nconversion completed.")
    print(f"total files: {total_files}")
    print(f"converted files: {converted_files}")
    print(f"failed conversions: {total_files - converted_files}")
    print(f"total time: {end_time - start_time:.2f} seconds")

使用脚本

input_dir = input("请输入包含 aac 文件的目录路径: ")
output_dir = input("请输入 mp3 文件的输出目录路径: ")
convert_aac_to_mp3(input_dir, output_dir)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com