Ai
1 Star 0 Fork 0

ddbetter-python/ffmpeg-demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
demo.py 3.07 KB
一键复制 编辑 原始数据 按行查看 历史
Joe 提交于 2021-10-17 21:47 +08:00 . ffmpeg
import subprocess
import imageio
import os
from PIL import Image
def find_file_name(file_path):
temps = file_path.split("/")
name = temps[len(temps)-1].split(".")[0]
print(temps)
return name
def concat_mp3(*mp3s, out_file):
"""
将多个mp3文件按照传入顺序合并到一起
"""
mp3str = "|".join(mp3s)
# acodec copy 重新编码并复制到新文件中
subprocess.call(
f'ffmpeg -i "concat:{mp3str}" -acodec copy {out_file}', shell=True)
def mix_mp3(*mp3s, out_file):
"""
将多个mp3文件混合到一起。目前测试有问题,不正确。
"""
mp3str = ""
for mp3 in mp3s:
mp3str = mp3str+" -i "+mp3
subprocess.call(
f'ffmpeg {mp3str} -filter_complex amix=inputs={len(mp3s)}:duration=first:dropout_transition=2 -f mp3 {out_file}', shell=True)
def video2mp3(file_name):
"""
将视频转为音频
:param file_name: 传入视频文件的路径
:return:
"""
outfile_name = file_name.split('.')[0] + '.mp3'
subprocess.call('ffmpeg -i ' + file_name +
' -f mp3 ' + outfile_name, shell=True)
def video_add_mp3(mp4_file, mp3_file, out_file):
"""
视频添加音频
:param file_name: 传入视频文件的路径
:param mp3_file: 传入音频文件的路径
:return:
"""
outfile_name = find_file_name(mp4_file) + '-txt.mp4'
# outfile_name = file_path.split('.')[0] + '-txt.mp4'
subprocess.call(
f'ffmpeg -i {mp4_file} -i {mp3_file} -strict -2 -f mp4 {out_file}', shell=True)
def compose_gif(file_path):
"""
将静态图片转为gif动图
:param file_path: 传入图片的目录的路径
:return:
"""
img_paths = sorted(
[int(p[3:-4]) for p in os.listdir(file_path) if os.path.splitext(p)[1] == ".png"])
img_paths = img_paths[:int(len(img_paths) / 3.6)]
gif_images = []
for path in img_paths:
gif_images.append(imageio.imread(
'{0}/out{1}.png'.format(file_path, path)))
imageio.mimsave("test.gif", gif_images, fps=30)
def compress_png(file_path):
"""
将gif动图转为每张静态图片
:param file_path: 传入gif文件的路径
:return:
"""
img_paths = [p for p in os.listdir(
file_path) if os.path.splitext(p)[1] == ".png"]
for filename in img_paths:
with Image.open('{0}/{1}'.format(file_path, filename)) as im:
width, height = im.size
new_width = 150
new_height = int(new_width * height * 1.0 / width)
resized_im = im.resize((new_width, new_height))
output_filename = filename
resized_im.save('{0}/{1}'.format(file_path, output_filename))
if __name__ == '__main__':
# video2mp3(file_name='data-a.mp4')
video_add_mp3(mp4_file='resources/mp4/0.mp4',
mp3_file='resources/mp3/m1.mp3', out_file="out/0-out.mp4")
# concat_mp3("2.mp3", "night.mp3", out_file="result.mp3")
# mix_mp3("resources/mp3/m1.mp3", "resources/mp3/m2.mp3", out_file="out/mix_result.mp3")
# compose_gif(file_path='merged')
# compress_png(file_path='merged')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/joe-python/ffmpeg-demo.git
git@gitee.com:joe-python/ffmpeg-demo.git
joe-python
ffmpeg-demo
ffmpeg-demo
master

搜索帮助