Home  >  Article  >  Backend Development  >  Python practical tutorial on batch conversion of multiple music formats

Python practical tutorial on batch conversion of multiple music formats

WBOY
WBOYforward
2023-04-12 12:16:141736browse

Python practical tutorial on batch conversion of multiple music formats

Pydub is a Python audio processing module based on ffmpeg. It encapsulates many ffmpeg underlying interfaces, so it is very convenient to use it to convert music and song file formats.

If you have read our previous articles, you know how powerful Pydub is.

Today I will introduce to you its music file format conversion function. It supports almost all music audio formats, which is very awesome.

1. Installation

Before installing Pydub, you need to install ffmpeg first:

(optional one) Mac (Open Terminal and install with homebrew):

brew install ffmpeg --with-libvorbis --with-sdl2 --with-theora

(optional two) Linux:

apt-get install ffmpeg libavcodec-extra

(optional three) Windows:

1. Enter http://ffmpeg.org/download.html#build-windows, click the icon corresponding to windows, enter the download interface and click the download button.

2. Unzip the downloaded zip file to the specified directory.

3. Add the bin directory (including ffmpeg.exe) in the decompressed file directory to the path environment variable.

(required) After successfully following the above ffmpeg installation steps, you can open the command prompt (cmd) or terminal (Terminal) and install pydub:

pip install pydub

2. mp3 Convert to wav or other formats

Convert a single mp3 audio file to wav audio format:

from pydub import AudioSegment
def trans_mp3_to_wav(filepath):
 """
 将mp3文件转化为wav格式
 Args:
 filepath (str): 文件路径
 """
 song = AudioSegment.from_mp3(filepath)
 filename = filepath.split(".")[0]
 song.export(f"{filename}.wav", format="wav")

You can continue to encapsulate this function to convert a single mp3 file to any other music audio format:

from pydub import AudioSegment
def trans_mp3_to_any_audio(filepath, audio_type):
 """
 将mp3文件转化为任意音频文件格式
 Args:
 filepath (str): 文件路径
 audio_type(str): 文件格式
 """
 song = AudioSegment.from_mp3(filepath)
 filename = filepath.split(".")[0]
 song.export(f"{filename}.{audio_type}", format=f"{audio_type}")

Such as ogg format:

trans_mp3_to_any_audio("Alone.mp3", "ogg")

As long as it is a music audio format supported by ffmpeg, it can convert it. There are dozens of supported formats. I will briefly list some below:

##flacapemp2aiff

##wav

avi

mp4

flv

##ogg

voc

au

3. 更加通用的转换函数

刚刚是mp3转任意音频格式,我希望把它写成任意音频格式转任意音频格式:

from pydub import AudioSegment
def trans_any_audio_types(filepath, input_audio_type, output_audio_type):
 """
 将任意音频文件格式转化为任意音频文件格式
 Args:
 filepath (str): 文件路径
 input_audio_type(str): 输入音频文件格式
 output_audio_type(str): 输出音频文件格式
 """
 song = AudioSegment.from_file(filepath, input_audio_type)
 filename = filepath.split(".")[0]
 song.export(f"{filename}.{output_audio_type}", format=f"{output_audio_type}")

比如将ogg音乐音频格式转化为flv音乐音频格式:

trans_any_audio_types("Alone.ogg", "ogg", "flv")

或者MP4格式,总之,一般你需要的格式它都能满足。

trans_any_audio_types("Alone.ogg", "ogg", "mp4")

4. 批量转化音频格式

现在,尝试将一个文件夹下的所有非mp3音频格式的文件转化为mp3音频格式:

def trans_all_file(files_path, target="mp3"):
 """
 批量转化音频音乐格式
 Args:
 files_path (str): 文件夹路径
 target (str, optional): 目标音乐格式. Defaults to "mp3".
 """
 for filepath in os.listdir(files_path):
 # 路径处理
 modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
 datapath = os.path.join(modpath, files_path + filepath)
 # 分割为文件名字和后缀并载入文件
 input_audio = os.path.splitext(datapath)
 song = AudioSegment.from_file(datapath, input_audio[-1].split(".")[-1])
 # 导出
 song.export(f"{input_audio[0]}.{target}", format=target)

只要输入文件夹名称,即可全部转化该文件夹下的音乐文件格式为mp3格式:

trans_all_file("F:\push\20200607\music\")

看了我们今天的教程,学会这招后,你再也不用担心格式之间的转化问题,通过使用 pydub模块你能轻易地解决这些问题。如果本篇文章对你有帮助,请在文末点个赞在看支持一下哦。

The above is the detailed content of Python practical tutorial on batch conversion of multiple music formats. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete