用循环连接.wav文件

2024-09-29 06:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有20秒的.wav文件,我需要结合起来,使20分钟长的文件。我有他们在修改日期的顺序,但没有在一个特定的方式命名(文件直接来自AudioMoth录音,可以尝试让他们重命名,如果需要的话)。 我已经研究了将它们结合起来的方法,我可以使用sox或ffmpeg,但是我有大约15000个文件,所以手动操作会花费一些时间。 希望它可能与一个循环?这是通过bash实现的,还是通过python或R实现的


Tags: 文件方法顺序方式时间手动命名ffmpeg
1条回答
网友
1楼 · 发布于 2024-09-29 06:24:10

下面是我将如何使用R和ffmpeg来实现这一点。我相信您可以使用bash执行相同类型的循环,但这似乎非常简单:

combiner <- function(path, segments_per_file) {
  ## Get a list of the wav files
  files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
  ## Split the list of wav files according to the number of files you want to combine at a time
  groups <- cumsum(seq_along(files) %% segments_per_file == 1)
  file_list <- split(files, groups)
  ## Loop through the list and use the concat protocol for ffmpeg to combine the files
  lapply(seq_along(file_list), function(x) {
    a <- tempfile(fileext = ".txt")
    writeLines(sprintf("file '%s'", file_list[[x]]), a)
    system(sprintf('ffmpeg -f concat -safe 0 -i %s -c copy Group_%s.wav', a, x))
  })
}

如果您更喜欢使用sox,那么循环更简单一些:

combiner <- function(path, segments_per_file) {
  files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
  groups <- cumsum(seq_along(files) %% segments_per_file == 1)
  file_list <- split(files, groups)
  lapply(seq_along(file_list), function(x) {
    system(sprintf("sox %s Group_%s.wav", paste(file_list[[x]], collapse = " "), x))
  })
}

在R中,如果您希望一次合并60个文件,则可以运行combiner(path_to_your_wav_files, 60)

请注意,组合文件将位于运行脚本的工作目录中(使用getwd()验证其位置)

相关问题 更多 >