Created
February 8, 2024 08:01
-
-
Save chen3feng/e857936f4aa0cf57291aabd692fada68 to your computer and use it in GitHub Desktop.
Merge MP3 files in archive packages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import glob | |
import os | |
import shutil | |
import subprocess | |
import sys | |
import rarfile | |
def expand_package(archive_file, basename) -> [str]: | |
with rarfile.RarFile(archive_file) as rar: | |
rar.extractall(basename) | |
return [f for f in glob.iglob(basename + '/**/*.mp3', recursive=True)] | |
def merge_mp3(files: [str], basename: str) -> str: | |
print(f'files={files}') | |
output_file = basename + '.mp3' | |
cmd = [ | |
'ffmpeg', | |
'-y', # Overwrite existing file | |
'-i', | |
f"concat:{'|'.join(files)}", | |
'-acodec', | |
'copy', output_file, | |
'-metadata', f'title="{basename}"', '-map_metadata', '0:-1', | |
] | |
subprocess.call(cmd) | |
return output_file | |
def merge_package(archive_file): | |
basename = os.path.splitext(os.path.basename(archive_file))[0] | |
files = expand_package(archive_file, basename) | |
merge_mp3(files, basename) | |
shutil.rmtree(basename, ignore_errors=True) | |
def merge_packages(archive_files): | |
for file in archive_files: | |
if '*' in file or '?' in file: | |
merge_packages(glob.glob(file)) | |
else: | |
merge_package(file) | |
def main(): | |
merge_packages(sys.argv[1:]) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Prerequisite
pip install rarfile
Make sure the executable file of
rar
or7z
in your path.sudo apt install unrar
Reference
https://blog.csdn.net/magic_ll/article/details/121676218
https://www.jianshu.com/p/ac643b0c6001
https://superuser.com/questions/314239/how-to-join-merge-many-mp3-files