手机缓存B站的视频并转成mp4 文件
环境:ubuntu20.04 , 手机缓存B站视频拷贝到电脑上发现音视频分开为audio.m4s,video.m4s. 于是用python写了一个脚本转成MP4
#1.安装ffmpeg
sudo apt-get install x264 libx264-de
mkdir ffmpeg
git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
cd ffmpeg
./configure --prefix=/usr/local/ffmpeg --enable-shared --disable-static --disable-doc --enable-gpl --enable-libx264
sudo make
sudo make install
sudo ln -s /usr/local/ffmpeg/bin/ffmpeg /usr/bin/ffmpeg
sudo ln -s /usr/local/ffmpeg/bin/ffprobe /usr/bin/ffprobe
sudo vi /etc/ld.so.conf
在其中添加路径: /usr/local/ffmpeg/lib
更新环境变量: sudo ldconfig
$ ffmpeg
ffmpeg version 4.4.git Copyright (c) 2000-2022 the FFmpeg developers
built with gcc 9 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
configuration: --prefix=/usr/local/ffmpeg --enable-shared --disable-static --disable-doc --enable-gpl --enable-libx264
libavutil 57. 27.100 / 57. 27.100
libavcodec 59. 33.100 / 59. 33.100
libavformat 59. 25.100 / 59. 25.100
libavdevice 59. 6.100 / 59. 6.100
libavfilter 8. 40.100 / 8. 40.100
libswscale 6. 6.100 / 6. 6.100
libswresample 4. 6.100 / 4. 6.100
libpostproc 56. 5.100 / 56. 5.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...
若出现上面的提示,则安装成功.
#2.用python 脚本执行转换
import os
import sys
import pandas as pd
import subprocess as sp
class BiliBili():
def __init__(self, dirName):
self.dirName = dirName
def renameDir(self):
for root, dirs, files in os.walk( self.dirName):
# print("【root】",root, " 【dirs】", dirs, " 【files】 ", files)
if 'entry.json' in files:
# print( root+'/'+'entry.json')
data=pd.read_json(root+'/'+'entry.json')
parentDirName = data.loc['part', 'page_data']
print( "【entry.json】",root," -重命名为-> ", os.path.dirname(root)+os.sep+parentDirName )
os.renames(root, os.path.dirname(root)+os.sep+parentDirName)
if 'video.m4s' in files:
print("【video.m4s】", root+os.sep+'video.m4s', " -重命名为-> ",root+os.sep+'video.m4v')
os.renames(root+os.sep+'video.m4s', root+os.sep+'video.m4v')
if 'audio.m4s' in files:
print("【audio.m4v】", root+os.sep+'audio.m4s', " -重命名为-> ",root+os.sep+'audio.m4a')
os.renames(root+os.sep+'audio.m4s', root+os.sep+'audio.m4a')
def buildMP4(self):
print( "build mp4 ")
for root, dirs, files in os.walk( self.dirName):
if 'video.m4v' in files and 'audio.m4a' in files:
print(root, files, type(files))
print( 'ffmpeg -i '+root+os.sep+'video.m4v -i '+root+os.sep+'audio.m4a'+' -codec copy '+root+os.sep+'../videoa.mp4')
p = sp.call('ffmpeg -i '+root+os.sep+'video.m4v -i '+root+os.sep+'audio.m4a'+' -codec copy '+root+os.sep+'../videoa.mp4', shell=True)
# p.wait()
if __name__ == '__main__':
bilibili = BiliBili("/home/用户/视频/bilibili/download")
bilibili.renameDir()
bilibili.buildMP4()
在BiliBili 这个类的初始化参数里填入 要转换的缓存视频路径。视频的名称放在entry.json 文件中,先用pandas读到文件名, 重命名文件夹,重命名音频文件名和视频文件名。这时候可以分别播放音频文件和视频文件了。但是不方便 ,我们还是用ffmpeg 合并音频文件和视频文件并转成MP4格式。结果如下。
参考:
《利用Python进行数据分析(第二版)》