python基于ffmpeg转换m4a为MP3

#!/usr/bin/python3
# _*_coding:utf-8 _*_

# @Time        :2021/4/11 19:38
# @Author    :jory.d
# @File        :m4a_to_mp3.py
# @Software    :PyCharm


"""
不能在pycharm里run, 只能在 cmd等终端里  python m4a_to_mp3.py
"""

import os
import os.path as osp
import glob
import re

ffmpeg_tool = "I:/ffmpeg/ffmpeg-4.1-win64-static/bin"


def func1():
    """
    把文件名的特殊字符去掉
    :return:
    """
    m4a_path = "H:/spider_download/qqmusic-20210411"
    for f in glob.glob(f'{m4a_path}/*.m4a'):
        fname = osp.basename(f)
        fname = re.findall(r'[^\*"/:?\\|<>]', fname, re.S)
        fname = "".join(fname)
        new_filepath = f'{osp.dirname(f)}/{fname}'
        print(f)
        print(new_filepath)
        os.rename(f, new_filepath)


def func2():
    '''
    m4a ---> mp3
    :return:
    '''
    m4a_path = "H:/spider_download/qqmusic-20210411"
    mp3_path = 'H:/spider_download/qqmusic-20210411-mp3'
    for f in glob.glob(f'{m4a_path}/*.m4a'):
        fname = osp.basename(f)
        mp3_filepath = f'{mp3_path}/{fname[:-4]}.mp3'
        os.makedirs(osp.dirname(mp3_filepath), exist_ok=True)
        print(mp3_filepath)
        cmd = f'{ffmpeg_tool}/ffmpeg -i {f} {mp3_filepath}'
        os.system(cmd)
        print(f'{fname} is converted.')

    print('Done.')


if __name__ == '__main__':
    # func1()
    func2()

 

posted @ 2021-04-11 20:04  dangxusheng  阅读(1073)  评论(0编辑  收藏  举报