目前手机版的b站缓存的文件是m4s格式的,并且将视频和音频分别存储,所以我瞎写了一个进行文件批量转码的代码,可以进行文件的转码和重命名,如果有什么问题的话,欢迎大伙交流
代码在进行文件编码时使用了ffmpeg,所以在运行代码前注意安装ffmpeg
import ffmpeg
import os
import json
import re
path = "E:\\testbili\\download"
result_file = "E:\\testbili\\download\\result" # 最终转码后文件的存储目录
file_num = 0
for root, dirs, files in os.walk(path): # 文件夹的遍历访问,访问逻辑类似深度优先遍历
if len(files) >= 1 and files[1] == "entry.json":
with open(os.path.join(root, files[1]), 'r+', encoding='utf-8') as f:
json_str = json.load(f) # 通过json.load()函数加载文件内容到变量中
try:
print(json_str['page_data']['download_subtitle'])
except KeyError:
str__name = json_str['owner_name'] + \
json_str['title']
# 通过对于json的分析我们可以发现其中的一部分内容存储在page_data对象中的download_subtitle键值对中,通过此方法进行访问
# 新文件名,使用+进行字符串的连接
else:
if json_str['page_data']['download_subtitle'] == "":
str__name = json_str['owner_name'] + \
json_str['title']
else:
str__name = json_str['owner_name'] + \
json_str['page_data']['download_subtitle']
pattern = re.compile(r'\w')
new_file_name = re.findall(pattern,str__name) # 最终视频文件的文件名
if len(files) >= 3 and files[0] == "audio.m4s" and files[2] == "video.m4s":
file_num += 1
print("root---", root)
audio_file = os.path.join(root, files[0]) # audio文件路径
video_file = os.path.join(root, files[2]) # video文件路径
temp_num = str(file_num)
temp_name = temp_num + ".mp4"
temp_file = os.path.join(result_file, temp_name)
file_name = new_file_name+".mp4" # 最终文件名
mp4_file = os.path.join(result_file, file_name) # 最终文件路径
command = f"ffmpeg.exe -i {audio_file} -i {video_file} -acodec copy -vcodec h264_nvenc {temp_file}"
# subprocess.run(command,shell=True)
# time.sleep(9)
os.system(command)
result_files = os.listdir(result_file)
if result_files.count(file_name) > 0:
print("出现重名文件")
file_name = new_file_name+temp_num+".mp4" # 最终文件名
mp4_file = os.path.join(result_file, file_name) # 最终文件路径
os.renames(temp_file, mp4_file)
else:
print("文件重命名")
os.renames(temp_file, mp4_file)
print("文件数目,应为...:", file_num)