python基于moviepy實現音視頻剪輯
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.優化:輸入輸出的合法性校驗
校驗輸入地址是合法文件 校驗時間段(沒什么必要) 不可以小于0不可以大于視頻時間起小于止完整代碼需要pip install moviepy
簡單的使用
from moviepy.editor import VideoFileClip, concatenate_videoclipsclipOri = 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 osimport moviepy.video.io.ffmpeg_tools as fftoolfrom moviepy.tools import cvsecsdef 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實現音視頻剪輯的資料請關注好吧啦網其它相關文章!
相關文章:
