實踐步驟
1.尋找合適的Python庫(安裝是否麻煩、使用是否簡便、執行會不會太久)
- moviepy 音視頻庫。分析需要用的API:代碼示例
2.定義輸入輸出
- 輸入:一個音視頻文件的地址,需要剪出來的時間段
- 輸出:剪輯片段的文件
3.設計執行流程并一步步實現(定義函數,與使用具體API相關)
- 讀入并創建clip對象。
- 剪輯subclip,輸入時間參數可以是時間格式的字符串。
- 導出write_videofile。
4.結論:時間太久,片段多長就花了多久的時間;CPU全跑滿了。
stackoverflowConcat videos too slow using Python MoviePY 里面有個答案說,調用包里封裝的ffmpeg函數會快一些:
You have some functions that perform direct calls to ffmpeg: github.com/Zulko/movie… And are therefore extremely efficient, for simple tasks such as yours.
5.重新設計和實現,直接使用moviepy.video.io.ffmpeg_tools里的函數:ffmpeg_extract_subclip(源音視頻文件,起,止,輸出名)。
- 這個函數中輸入的起止時間參數只能是數字,不能是字符串,而庫基本使用的接口函數傳入的是字符串。看源碼發現是有個把時間字符串轉換成數字的裝飾器的,一步步找就可以找到那個轉換的函數了。
6.結論:時間快了很多,幾乎是幾秒內就完成。
7.優化:一次處理多個時間段
- 輸入由一個起止時間,變為一組起止時間
- 循環處理每一組起止時間
- 輸出的文件名按順序拼接
8.優化:每段時間配上名字
- 輸入除了每一組的起止時間,還有后綴名
- 文件名+后綴得到輸出的文件名
9.優化:輸入輸出的合法性校驗
完整代碼
需要pip install moviepy
簡單的使用
from moviepy.editor import VideoFileClip, concatenate_videoclips
clipOri = VideoFileClip("E:/2020-03-29 19-31-39.mkv")
#截取兩個subclip再拼接
#time_length = int(clipOri.duration) 這句可以獲取片子的時
#超過時長會報錯,時長默認用秒,也可以寫得更細,(00:03:50.54)->3分50秒
cut1 = clipOri.subclip(0, 7053)
cut2 = clipOri.subclip(7059, 8941)
finalClip = concatenate_videoclips([cut1,cut2])
finalClip.write_videofile("E:/acut.mp4")
import os
import moviepy.video.io.ffmpeg_tools as fftool
from moviepy.tools import cvsecs
def add_suffix(file_name, suffix): # 文件名拼接后綴
index = file_name.rfind('.') # 最后一個點號
res = file_name[:index] + '_' + suffix + file_name[index:]
return res
# 輸入
file_name = r"./XXX.mkv"
output_arr = [
('04:20','05:07', '自我介紹'),
('05:07','17:47', '項目經歷'),
('17:37','24:40', 'HTTPS'),
('24:40','28:10', '實現讀寫鎖'),
]
if not os.path.isfile(file_name): # 校驗
print("不合法的輸入", file_name)
for startStr, endStr, suffix in output_arr:
start = cvsecs(startStr)
end = cvsecs(endStr)
if start 0 or start >= end: # 校驗
print("不合法的時間",startStr, endStr)
continue
full_output_name = add_suffix(file_name, suffix)
print('處理文件:', file_name, '時間:', startStr, '-', endStr)
fftool.ffmpeg_extract_subclip(file_name,start,end,full_output_name) # 剪輯并輸出
print('處理功成功,輸出:',full_output_name)
參考
- moviepy的文檔
- moviepy中文文檔
- 英文文檔
- GitHub地址
- 博文:用moviepy將視頻剪掉一段
- stack overflow Concat videos too slow using Python MoviePY
以上就是python基于moviepy實現音視頻剪輯的詳細內容,更多關于python moviepy實現音視頻剪輯的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- python用moviepy對視頻進行簡單的處理
- MoviePy常用剪輯類及Python視頻剪輯自動化
- MoviePy簡介及Python視頻剪輯自動化
- Python視頻編輯庫MoviePy的使用
- Python使用pydub模塊轉換音頻格式以及對音頻進行剪輯
- Python竟然能剪輯視頻
- 用python進行視頻剪輯