Python實(shí)現(xiàn)vlog生成器的示例代碼
Python實(shí)現(xiàn)vlog生成器
vlog,全稱(chēng)為Video blog,意為影音博客,也有翻譯為微錄。
本文將嘗試用Python基于Moviepy從一個(gè)文本文件中自動(dòng)生成一個(gè)視頻格式的vlog,實(shí)現(xiàn)的功能如下:
- 將文件的第一行標(biāo)題生成視頻的片頭
- 將文件中圖片和文字轉(zhuǎn)成視頻并生成音頻和字幕
- 將文件中視頻片段或gif拼接到視頻中
- 自動(dòng)添加一個(gè)片尾
效果如下:

1. 文本格式
平時(shí)習(xí)慣用markdown進(jìn)行寫(xiě)作,所以這里也選擇markdown作為文本格式。定義格式如下:
- 第一行為視頻的標(biāo)題
- 從第二行開(kāi)始是視頻的內(nèi)容
- 視頻內(nèi)容分兩種格式,一種圖片加文字,一種視頻或gif。第一種是一張圖片后面加一行文字說(shuō)明,視頻或gif沒(méi)有文字說(shuō)明

接下來(lái)按上面的格式實(shí)現(xiàn)代碼。
2. 內(nèi)容解析
第一步是將markdown解析成Python的一個(gè)字典對(duì)象。字典對(duì)象包括*標(biāo)題(title)和內(nèi)容(content)*兩部分。標(biāo)題是一個(gè)文本值,內(nèi)容是一個(gè)列表,包括一些圖片加文字或視頻片段。
解析過(guò)程如下:
2.1 讀取文件,將第一行去除不需要的字符作為標(biāo)題;
2.2 遍歷文件,提取文件后綴,根據(jù)文件后綴判斷是否是視頻還是圖片,如果是圖片就將下一行作為解說(shuō)文字;
2.3 不斷解析直至文件結(jié)束。
代碼如下:
def parse(filename):
result = {
"title": "",
"content": []
}
with open(filename) as f:
lines = f.readlines()
title = lines[0].strip('#').strip()
result['title'] = title
content = list(filter(lambda x: x.strip() != '', lines[1:]))
print(content)
i = 0
while i < len(content):
s = content[i]
link = s[s.find("(")+1:s.find(")")]
text = s[s.find("[") + 1:s.find("]")]
i += 1
if link.endswith(".mp4") or link.endswith(".gif"):
result['content'].append({
'link': link,
'text': text,
'type': 'video'
})
else:
subtitle = content[i].strip()
i += 1
result['content'].append({
'link': link,
'text': text,
'subtitle': subtitle,
'type': 'image'
})
return result
3. 生成片頭
解析完成后開(kāi)始根據(jù)內(nèi)容生成視頻,先用標(biāo)題生成片頭并添加動(dòng)態(tài)效果,代碼如下:
def generate_title(title):
print(f"title: {title}")
def cascade(screenpos, i):
v = np.array([0, -1])
d = lambda t: 1 if t < 0 else abs(np.sinc(t) / (1 + t ** 4))
return lambda t: screenpos + v * 400 * d(t - 0.15 * i)
def move_letters(letters, funcpos):
return [letter.set_pos(funcpos(letter.screenpos, i))
for i, letter in enumerate(letters)]
size = (1280, 720)
title_clip = TextClip(title, color=config.TITLE['color'],
font=config.TITLE['font'], kerning=5,
fontsize=config.TITLE['font-size'])
cvc = CompositeVideoClip([title_clip.set_pos('center')], size=size)
letters = findObjects(cvc)
clip = CompositeVideoClip(move_letters(letters, cascade), size=size).subclip(0, 5)
return clip
4.視頻片段生成
片頭之后是內(nèi)容片段的生成,內(nèi)容片段如果是視頻直接讀取即可,如果是圖片需要將圖片配上語(yǔ)音并添加字幕,代碼如下:
def generate_clip_with_subtitle(image_path, text):
print(f"clip text: {text}")
clip = ImageClip(image_path)
audio = AudioFileClip(text2wav(text))
txt_clip = TextClip(text.replace(" ", ""), font=config.SUBTITLE['font'],
color=config.SUBTITLE['color'], fontsize=config.SUBTITLE['font-size'])
vtuber_clip = get_vtuber(audio.duration)
video = CompositeVideoClip([clip, txt_clip.set_pos(('center', 'bottom')),
vtuber_clip.set_pos(('right', 'bottom'))])
video.audio = audio
video.duration = audio.duration
return video
5.生成片尾
內(nèi)容片段生成完成后,再添加一個(gè)簡(jiǎn)單的片尾,這里添一個(gè)加文字片尾,代碼如下:
def generate_ending(text="聽(tīng)說(shuō)點(diǎn)贊帶來(lái)好運(yùn)"):
print(f"ending: {text}")
size = (1280, 720)
title_clip = TextClip(text, color=config.ENDING['color'], font=config.ENDING['font'],
kerning=5, fontsize=config.ENDING['font-size'])
clip = CompositeVideoClip([title_clip.set_pos('center')], size=size)
clip.duration = 1
return clip
6.完整視頻合成
最后就是整合上面的代碼,并將上面生成視頻片段合并成一個(gè)完整的視頻,代碼如下:
def generate_vlog(filename, output_path):
clips = []
result = parser.parse(filename)
title_clip = generate_title(result['title'])
clips.append(title_clip)
for item in result['content']:
if item['text']:
clips.append(generate_text_clip(item['text']))
if item['type'] == 'image':
clips.append(generate_clip_with_subtitle(item['link'], item['subtitle']))
elif item['type'] == 'video':
clips.append(load_video(item['link']))
clips.append(generate_ending())
video = concatenate_videoclips(clips, method="compose")
video.write_videofile(output_path, fps=24, audio_codec="aac")以上就是Python實(shí)現(xiàn)vlog生成器的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Python vlog生成器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python3使用騰訊企業(yè)郵箱發(fā)送郵件的實(shí)例
今天小編就為大家分享一篇python3使用騰訊企業(yè)郵箱發(fā)送郵件的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
Django migrate報(bào)錯(cuò)的解決方案
在講解如何解決migrate報(bào)錯(cuò)原因前,我們先要了解migrate做了什么事情,本文就詳細(xì)的介紹migrate使用以及出現(xiàn)問(wèn)題的解決,感興趣的可以了解一下2021-05-05
解決Python復(fù)雜zip文件的解壓?jiǎn)栴}
這篇文章主要介紹了Python復(fù)雜zip文件的解壓,通過(guò)配合 shutil 與 os 標(biāo)準(zhǔn)庫(kù)中的相關(guān)功能,實(shí)現(xiàn)將指定任意 zip 壓縮包,完好地解壓到指定的目錄中,需要的朋友可以參考下2021-12-12
Python辦公自動(dòng)化處理的10大場(chǎng)景應(yīng)用示例
這篇文章主要為大家介紹了Python辦公自動(dòng)化處理的10大場(chǎng)景應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

