今天在用python的moviepy库给视频加字时遇到两个问题,把解决方法记录下来。
一。使用TextClip.list('font')时报错
出错代码
from moviepy.editor import *
TextClip.list('font')
错误信息
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\fyr\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1208, in list
return [l.decode('UTF-8')[8:] for l in lines if l.startswith(b" Font:")]
File "C:\Users\fyr\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1208, in
return [l.decode('UTF-8')[8:] for l in lines if l.startswith(b" Font:")]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x98 in position 8: invalid start byte
解决办法
首先定位到moviepy\video\VideoClip.py, line 1208,用编辑器打开,找到如下代码
if arg == 'font':
return [l.decode('UTF-8')[8:] for l in lines if l.startswith(b" Font:")]
在Windows上decode('UTF-8')会出错,替换为ANSI编码
if arg == 'font':
#return [l.decode('UTF-8')[8:] for l in lines if l.startswith(b" Font:")]
return [l.decode('ANSI')[8:] for l in lines if l.startswith(b" Font:")]
保存即可
二。使用CompositeVideoClip()时报错
出错代码
main_clip = VideoClip(make_frame, duration=int(len(active_data) / output_FPS))
text_clip = TextClip("Hello", fontsize=70, stroke_width=5, color='white')
final_clip = CompositeVideoClip([main_clip, text_clip.set_pos(("left","top"))])
final_clip.set_duration(main_clip.duration)
final_clip.write_videofile(filename, fps=output_FPS)
错误信息
Traceback (most recent call last):
File "d:/Documents/pplab/Software/HandRecognition/main.py", line 340, in
render.renderToMP4(resample_data, "result.mp4")
File "d:\Documents\pplab\Software\HandRecognition\render.py", line 59, in renderToMP4
final_clip.write_videofile(filename, fps=output_FPS)
File "", line 2, in write_videofile
File "C:\Users\fyr\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\decorators.py", line 52, in requires_duration
raise ValueError("Attribute 'duration' not set")
ValueError: Attribute 'duration' not set
即便使用了set_duration(),依然报错 'duration' not set
解决办法
定位到moviepy\video\compositing\CompositeVideoClip.py, line 47,找到如下代码
def __init__(self, clips, size=None, bg_color=None, use_bgclip=False,
ismask=False)
加一个duration参数,修改为
def __init__(self, clips, size=None, bg_color=None, use_bgclip=False,
ismask=False, duration=1)
然后在当前文件line 73处附近找到
VideoClip.__init__(self)
self.size = size
self.ismask = ismask
self.clips = clips
self.bg_color = bg_color
加一行self.duration = duration
VideoClip.__init__(self)
self.size = size
self.ismask = ismask
self.clips = clips
self.bg_color = bg_color
self.duration = duration
保存文件,并注意使用CompositeVideoClip时加上duration参数
final_clip = CompositeVideoClip([main_clip, text_clip.set_pos(("left","top"))], duration=main_clip.duration)