視頻分割
實現方式
爲了實現簡單,這裏採用Python實現視頻的分割,在java中調用Python腳本。
Python實現
安裝moviepy庫
源的選擇
- 清華的很快,但是下載imageio的時候,卡在99%
- USTC的源速度很快,但找不到imageio
- 阿里雲的源速度一般,但是目前最靠譜。
創建pip配置文件
vim ~/.pip/pip.conf
編寫文件內容如下
[global]
timeout = 6000
index-url = https://mirrors.aliyun.com/pypi/simple
[install]
use-mirrors = true
mirros = https://pypi.mirrors.ustc.edu.cn/simple
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple moviepy
Python代碼
第一次運行報錯
import moviepy
import miageio
from moviepy.editor import *
video = VideoFileClip("video.mp4").subclip(108,138)
result = CompositeVideoClip([video,])
reslut.to_videofile("video_1.mp4")
提示“imageio.core.fetching.NeedDownloadError: Need ffmpeg exe. You can download it by calling: imageio.plugins.ffmpeg.download()”
解決方法:
在代碼中添加iamgeio.plugins.ffmpet.download()
import moviepy
import miageio
iamgeio.plugins.ffmpeg.download()
from moviepy.editor import *
video = VideoFileClip("video.mp4").subclip(108,138)
result = CompositeVideoClip([video,])
reslut.to_videofile("video_1.mp4")
第一次運行,因爲要下載imageio.plugins.ffmpeg,速度很慢。
以後運行,感覺效率也不是很好。只能作爲一個暫時的解決方法吧!
在Java中調用Python腳本
String path_to_cut_py = "/home/huyahui/jars/py/cut_video.py";
try{
System.out.println("Cut video :" + local_path + " start");
String[] args = new String[]{"python", path_to_cut_py};
Process pr = Runtime.getRuntime().exec(args);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("Cut video end. return: " + pr.exitValue());
}catch (Exception e) {
e.printStackTrace();
}
腳本路徑一定要用絕對路徑?
反正調用腳本時,路徑寫爲
~/jars/*.py
是不能調的
出現了一個新的問題單獨執行Python腳本可以,但是在Java中調用執行到一半就退出了。
懷疑還是路徑的問題,這次是Python腳本中的路徑的問題。到路徑哪一句就卡住了。
果然!我們把Python腳本的錯誤輸出後,
用pr.getErrorStream() 來獲取pr的錯誤輸出。就可以發現出現了以下錯誤
Traceback (most recent call last):
File "/home/huyahui/jars/py/cut_video.py", line 12, in <module>
video = VideoFileClip("video.mp4").subclip(108, 138)
File "/home/huyahui/.local/lib/python2.7/site-packages/moviepy/video/io/VideoFileClip.py", line 81, in __init__
fps_source=fps_source)
File "/home/huyahui/.local/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 32, in __init__
fps_source)
File "/home/huyahui/.local/lib/python2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 272, in ffmpeg_parse_infos
"path.")%filename)
IOError: MoviePy error: the file video.mp4 could not be found !
Please check that you entered the correct path.
將Python腳本中的文件路徑修改爲./video.mp4
也不行。改爲絕對路徑後就可以了,這個問題不大,反正真正使用的時候我們傳入的就是絕對路徑。
終於成功生成了!