B站windows客户端视频解码
import os
import json
# 只获取文件夹的列表,已排除单个文件
def get_folder_list(rootdir): return [os.path.join(rootdir, name) for name in os.listdir(
rootdir) if os.path.isdir(os.path.join(rootdir, name))]
def fix_m4s(target_path: str, output_path: str, bufsize: int = 256*1024*1024) -> None:
assert bufsize > 0
with open(target_path, 'rb') as target_file:
header = target_file.read(32)
new_header = header.replace(b'000000000', b'')
new_header = new_header.replace(b'$', b' ')
new_header = new_header.replace(b'avc1', b'')
with open(output_path, 'wb') as output_file:
output_file.write(new_header)
i = target_file.read(bufsize)
while i:
output_file.write(i)
i = target_file.read(bufsize)
folderList = get_folder_list("D:/Video/bilibili/")
exist_transed_folder_list = get_folder_list("D:/Video/Trans/")
# 获取所有已转换的文件的文件名
exist_transed_video_list = [os.path.splitext(f)[0] for folder in exist_transed_folder_list for f in os.listdir(
folder) if f.endswith('.mp3') or f.endswith('.mp4')]
count = 0 # 计数用
all = len(folderList) - len(exist_transed_folder_list)
for folder in folderList:
print(folder) # 当前操作的目录
# 找到所有的m4s文件
m4s_files = [folder+'/' +
file for file in os.listdir(folder) if file.endswith('.m4s')]
# 读取videoinfo信息
with open(folder+'/.videoInfo', 'r', encoding='utf-8') as f:
videoinfo = json.loads(f.read())
bvid = videoinfo["bvid"]
p = videoinfo["p"]
tabName = videoinfo["tabName"]
output_dir = "D:/Video/Trans/" + bvid
if not os.path.exists(output_dir):
os.makedirs(output_dir)
elif output_dir in exist_transed_folder_list:
continue
fix_m4s(m4s_files[0], output_dir + '/' + str(p) + '_' + tabName + '.mp4')
fix_m4s(m4s_files[1], output_dir + '/' + str(p) + '_' + tabName + '.mp3')
在最后两行没对文件做判断,但是我用potplayer播放了没问题。
下载的文件里面有两个.m4s文件,文件名倒数第3位是2表示音频文件,0表示视频文件,可以自己做个判断再修改后缀。
核心代码是下面这三行替换,来源于B站的一个视频以及评论区,视频已经找不到是哪个了。
思想就是把.m4s以二进制格式打开,前9个0删掉,$改成空格,avc1删掉,就完事儿了。
new_header = header.replace(b'000000000', b'')
new_header = new_header.replace(b'$', b' ')
new_header = new_header.replace(b'avc1', b'')
放个图片做封面