我可以像使用 ffmpeg 一样使用 R 来 trim 视频吗?

Can I use R to trim a video, like I do with ffmpeg?

我有几个视频文件需要 trim/cut(即,在 2 小时长的视频中剪切 00:05:00 - 00:10:00)。我可以使用 ffmpeg trim/cut 每个视频。但是,由于我有 +100 个视频文件需要 trimmed,所以我想使用 R 循环功能来完成它。

我发现人们使用多种 R 包进行视频处理,例如 imager 或 magick,但我找不到使用 R trim 视频的方法。

你能帮帮我吗?谢谢!

使用 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 包,但我一直更喜欢在终端使用循环或使用 sprintf 创建命令 运行 并使用system().