[英]Can I use R to trim a video, like I do with ffmpeg?
我有几个视频文件需要修剪/剪切(即,在 2 小时长的视频中剪切 00:05:00 - 00:10:00)。 我可以使用 ffmpeg 修剪/剪切每个视频。 但是,由于我有 +100 个视频文件需要修剪,我想使用 R 循环 function 来做。
我发现有几个 R 软件包可供人们用于视频处理,例如 imager 或 magick,但我找不到使用 R 修剪视频的方法。
你能帮助我吗? 谢谢!
使用ffmpeg
修剪视频的基本方法如下:
ffmpeg -i input.mp4 -ss 00:05:00 -to 00:10:00 -c copy output.mp4
要创建批处理文件,您可以将以下内容放入文本文件并将其另存为“trimvideo.bat”之类的内容并在相关文件夹中运行。
@echo off
:: loops across all the mp4s in the folder
for %%A in (*.mp4) do ffmpeg -i "%%A"^
:: the commands you would use for processing one file
-ss 00:05:00 -to 00:10:00 -c copy ^
:: the new file (original_trimmed.mp4)
"%%~nA_trimmed.mp4"
pause
如果您想通过 R 执行此操作,您可以执行以下操作:
# get a list of the files you're working with
x <- list.files(pattern = "*.mp4")
for (i in seq_along(x)) {
cmd <- sprintf("ffmpeg -i %s -ss 00:05:00 -to 00:10:00 -c copy %_trimmed.mp4",
x[i], sub(".mp4$", "", x[i]))
system(cmd)
}
过去,当我想从一个文件或多个文件中剪切特定部分时,我曾使用过类似的方法。 在这些情况下,我从类似于以下内容的data.frame
开始:
df <- data.frame(file = c("file_A.mp4", "file_B.mp4", "file_A.mp4"),
start = c("00:01:00", "00:05:00", "00:02:30"),
end = c("00:02:20", "00:07:00", "00:04:00"),
output = c("segment_1.mp4", "segment_2.mp4", "segment_3.mp4"))
df
# file start end output
# 1 file_A.mp4 00:01:00 00:02:20 segment_1.mp4
# 2 file_B.mp4 00:05:00 00:07:00 segment_2.mp4
# 3 file_A.mp4 00:02:30 00:04:00 segment_3.mp4
我使用sprintf
创建要运行的ffmpeg
命令:
cmds <- with(df, sprintf("ffmpeg -i %s -ss %s -to %s -c copy %s",
file, start, end, output))
cmds
# [1] "ffmpeg -i file_A.mp4 -ss 00:01:00 -to 00:02:20 -c copy segment_1.mp4"
# [2] "ffmpeg -i file_B.mp4 -ss 00:05:00 -to 00:07:00 -c copy segment_2.mp4"
# [3] "ffmpeg -i file_A.mp4 -ss 00:02:30 -to 00:04:00 -c copy segment_3.mp4"
我使用lapply(..., system)
运行它:
lapply(cmds, system)
您还可以查看av
package,但我一直更喜欢在终端使用循环或使用sprintf
和使用system()
创建要运行的命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.